gpt4 book ai didi

java - 仅显示对象名称调用的类方法

转载 作者:行者123 更新时间:2023-12-03 23:02:04 26 4
gpt4 key购买 nike

我有如下一段代码

public class DriverTester {
public static void main(...){
// test empty constructor
Person p1 = new Person();
System.out.println("p1: " + p1);
}
}

public class Person {
private String name;
// Empty constructor
public Person () {
}
// getter avoided for simplicity
public String toString() {
return "Mr.or Ms. "+this.name;
}
}

它编译、运行成功并显示“Mr or Mrs null”。因此,这将是调用 toString 方法的结果。

我不明白 print line 方法的语法。对象 p1 的名称如何运行给定的方法。它如何知道运行哪个方法?语法不应该是

System.out.println("p1: " + p1.getName());

System.out.println("p1: " + p1.toString());

感谢任何澄清

最佳答案

当连接字符串时,例如在这一行中:

System.out.println("p1: " + p1);

Java 将调用toString() 方法将任何对象转换为String 以进行连接。 Java 确保此方法存在于所有对象上,因为它是在 Object 上定义的类,每个类都隐式继承自该类。

此外,如果连接了一个null,Java 会将其转换为String “null”

Java Language Specification, section 5.1.11 ,涵盖“字符串转换”:

  • If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
  • Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

关于java - 仅显示对象名称调用的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16841057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com