java - 为什么调用Java对象实例会执行对象的方法

标签 java class methods

我目前正在学习Java,对某段代码感到困惑。我有 C、Python 背景,所以我更多地学习 Java 的语法和小领域。

下面我有两个类。我的 Main 类和一个包含返回该类的修饰输入字符串的方法的类。

我很困惑为什么调用 myObject 会自动调用返回消息的“toString()”方法?我是否应该需要定义要在对象上调用的方法?为什么用 Java 可以做到这一点?

我认为这是因为该类被称为“OtherClass”,并且 OtherClass 内部的方法被称为“OtherClass”,但是当我用另一个类测试这个假设时,调用该对象会返回该对象及其地址位置。

任何帮助都会很棒。谢谢!

public class HelloWorld
{
  public static void main(String[] args)
  {
    int i = 0;
    OtherClass myObject = new OtherClass("Hello World!");
    // This calls method toString()
    System.out.print(myObject);

    // This calls method toString()
    System.out.print(myObject.toString());
  }
}

public class OtherClass
{
  private String message;
  private boolean answer = false;
  public OtherClass(String input)
  {
    message = "Why, " + input + " Isn't this something?\n";
  }
  public String toString()
  {
    return message;
  }
}

最佳答案

public void print(Object obj)

Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

public static String valueOf(Object obj)

Returns the string representation of the Object argument.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

@Andreas评论中说,如果子类没有重写此方法,toString() 将打印哈希码:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

关于java - 为什么调用Java对象实例会执行对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37406776/

相关文章:

java 模拟带有重定向的post表单

java - 访问其他地方的类的字段?

c++ - 如何使用字符串返回一个指向对象的唯一指针 vector 的迭代器来查找对象?

java - 同时调用时的 JVM 方法调用内部结构

java - JTable过滤器-替换外来字符

java - 在不获取新内存地址的情况下在其他线程中加载位图

java - 使用mapTree集合并需要更多颜色

IOS - 从 IOS 应用程序中的另一个类写入 UITextField

java - 重写构建器中的方法

objective-c - Objective-C 类的方法存储在哪里以及如何存储?