我是 Java 新手,我正在尝试解决教授给出的练习。 他上过这门课
public class MioPunto {
public int x;
public int y;
public String toString() {
return ("[" + x + "," + y + "]");
}
}
我应该用 main 方法编写另一个类。在 main 中,我必须在不显式调用“toString”方法的情况下打印坐标。 我不知不觉就这样解决了
public class TestMioPunto{
public static void main(String[] args){
MioPunto inizio = new MioPunto();
MioPunto fine = new MioPunto();
inizio.x=10;
inizio.y=10;
fine.x=20;
fine.y=30;
System.out.println("Inizio: " + inizio + "\n" + "Fine: " + fine);
}
}
最佳答案
当您在 String
和对象上使用 +
时,Java 会调用 toString
。
所以你的
System.out.println("Inizio: " + inizio + "\n" + "Fine: " + fine);
与
相同System.out.println("Inizio: " + inizio.toString() + "\n" + "Fine: " + fine.toString());
异常(exception),如果 inizio
或 fine
为 null
,第一个不会给您错误(您会在字符串中看到 null
),但第二个会看到。
摘自 JLS 的 the String Concatenation operator 部分:
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
指的是String Conversion section ,其中表示(在讨论将基元转换为字符串之后):
...
Now only reference values need to be considered:
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 - 从 main 隐式调用类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47727944/