java - 从 main 隐式调用类中的方法

标签 java class methods program-entry-point

我是 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);
  }
}

输出为enter image description here 我不明白Java如何自动调用toString方法(括号和逗号),你能解释一下吗?

最佳答案

当您在 String 和对象上使用 + 时,Java 会调用 toString

所以你的

System.out.println("Inizio: " + inizio + "\n" + "Fine: " + fine);

相同
System.out.println("Inizio: " + inizio.toString() + "\n" + "Fine: " + fine.toString());

异常(exception),如果 iniziofinenull,第一个不会给您错误(您会在字符串中看到 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/

相关文章:

java - Java/OOP 编程中传递参数、好的和坏的实践

java - 如何将Oracle11g UCM自定义服务调用到另一个自定义组件的Java代码中?

java - 如何在 javafx 中创建一个弹出窗口

java - Java 有没有办法让编译器处理互斥的选项?

c++ - 从类 C++ 返回映射

java - 错误检查未注册

Python - Google App Engine - Django 模板中的方法

java - 使用Eclipse导入用户定义的Java类的问题

java - 使用 SQL 时,我应该如何处理 TableModel 更新?

ruby - 如何包含来自其他模块的 Ruby 类扩展?