简体   繁体   English

为什么没有调用A类中的toString?

[英]Why is toString in class A evoked even though it is not called?

public class Test {
    public static void main(String[] args) {
        Object a1 = new A();
        Object a2 = new Object();
        System.out.println(a1);
        System.out.println(a2);
    }
}

class A {
    int x;

    public String toString() {
        return "A's x is " + x;
    }
}

Output 输出量

A's x is 0 A的x是0

java.lang.Object@1edf1c96 java.lang.Object@1edf1c96

When a1 is printed, the toString() method inside class A is called without being explicitly called. 打印a1时,将调用类A中的toString()方法,而无需显式调用它。 Can you please explain to me how that happens. 你能告诉我这是怎么发生的。

The toString() is implicitly called by println(Object) . toString()println(Object)隐式调用。 Obviously, because it needs to display a String , and toString() is guaranteed to return some form of String representation for all objects. 显然,因为它需要显示String ,所以保证toString()返回所有对象的某种形式的String表示形式。

As you can read in the documentation of PrintStream.println(Object) : 正如您可以在PrintStream.println(Object)的文档中阅读的那样:

public void println(Object x)

Print an Object and then terminate the line. 打印一个对象,然后终止该行。 This method behaves as though it invokes print(Object) and then println() . 此方法的行为就像先调用print(Object)然后调用 println()

Parameters: 参数:
x - The Object to be printed. x要打印的对象。

Now if we take a look at PrintStream.print(Object) , we see: 现在,如果我们看一下PrintStream.print(Object) ,我们将看到:

public void print(Object obj)

Print 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. 根据平台的默认字符编码, String.valueOf(Object)方法生成的字符串转换为字节,然后以write(int)方法的方式完全写入这些字节。

Parameters: 参数:
obj - The Object to be printed obj要打印的对象

Now as you can see, internally the String.valueOf(object) is called, which is defined as: 现在您可以看到,内部调用了String.valueOf(object) ,其定义为:

public static String valueOf(Object obj)

Returns the string representation of the Object argument. 返回Object参数的字符串表示形式。

Parameters: 参数:
obj - an Object. obj一个对象。
Returns: 返回值:
if the argument is null , then a string equal to "null" ; 如果参数为null ,则字符串等于"null" ; otherwise, the value of obj.toString() is returned. 否则,返回obj.toString()的值。

So that means that if you write something like: 因此,这意味着如果您编写如下内容:

System.out.println(foo);

You actually have written something equivalent to: 您实际上已经写了相当于

System.out.print(foo);
System.out.println();

which expand further into: 进一步扩展为:

System.out.print(String.valueOf(foo));
System.out.println();

which expands into: 扩展为:

if(foo == null) {
    System.out.print("null");
} else {
    System.out.print(foo.toString());
}
System.out.println();

Or to make it more clear. 或者说得更清楚些。 In the code of PrintStream , you will see something like: PrintStream的代码中,您将看到类似以下内容的内容:

public class PrintStream {

    // ...

    public void println(Object x) {
        this.print(x);
        this.println();
    }

    public void print(Object obj) {
        String result = String.valueOf(obj);
        // ... do something with result (print it to the stream)
    }

}

and in String you will find something like: String您会发现类似以下内容:

public class String {

    // ...

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

}

The toString() method is defined in every Object . 在每个Object中都定义了toString()方法。 Its default behavior is to return a string representation of that object like "java.lang.Object@1edf1c96" . 它的默认行为是返回该对象的字符串表示形式,例如"java.lang.Object@1edf1c96"

In your A class you just replaced this behavior with a new one, by redefining the toString() method ("redefining" means defining that method again in a subclass using the same signature). 在您的A类中,您只是通过重新定义toString()方法而用新的行为替换了该行为(“重新定义”意味着使用相同的签名在子类中再次定义该方法)。

This is called Override . 这称为Override

When you print an object, the println() method will blindly call the toString() method of the object, without knowing (or caring) if it was redefined or not. 当您打印对象时, println()方法将盲目调用对象的toString()方法,而不知道(或关心)是否已重新定义该对象。

If you want to represent any object as a string, toString() method comes into existence. 如果要将任何对象表示为字符串,则存在toString()方法。

The toString() method returns the string representation of the object. toString()方法返回对象的字符串表示形式。

If you print any object, java compiler internally invokes the toString() method on the object. 如果打印任何对象,则Java编译器会在内部调用该对象的toString()方法。 So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation. 因此,重写toString()方法,返回所需的输出,它可以是对象的状态,等等。这取决于您的实现。

By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code. 通过重写Object类的toString()方法,我们可以返回对象的值,因此无需编写太多代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么String类是不可变的,即使它有一个名为“hash”的非最终字段 - Why String class is immutable even though it has a non -final field called “hash” 为什么(在某些情况下)即使禁用了日志记录级别,logback也不会调用toString()? - Why (in some cases) does logback invoke toString() even though logging level is disabled? 为什么 Vert.x 被称为响应式,即使它是单线程的 - Why is Vert.x called responsive even though it is single threaded 为什么@SpringBootApplication类中声明的bean即使不是构造型类也要注册? - Why is a bean declared in @SpringBootApplication class registered even though it is not a stereotyped class? 即使发生错误也会调用 then() - then() is called even though error is occured 为什么不为函数参数调用toString? - Why toString is not called for functions parameter? 为什么.isNotNull(); 即使我有 controller class,断言也会失败? - Why .isNotNull(); assertions fails even though I have a controller class? Document.toString() 是 "[#document: null]" 即使 XML 被解析 - Document.toString() is "[#document: null]" even though XML was parsed 为什么扩展Abstract类的类中的方法即使未调用也仍在运行? - Why are methods in class that extends Abstract class running even when not called? Java-为什么即使调用了有效的资源也要执行自定义404错误页面? - Java - Why custom 404 error page is being executed even though a valid resourse is called?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM