gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:36:21 25 4
gpt4 key购买 nike

我目前正在学习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/

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