简体   繁体   English

为什么print语句在Java中调用** toString **方法?

[英]Why print statement calls **toString** method in java?

Why the following code segment auto calls toString() method? 为什么以下代码段会自动调用toString()方法?

Code: 码:

public class Demo {
   public Demo() {
    System.out.println(this); // Why does this line automatically calls toString()?
    }

   public static void main(String[] args) {
    Demo dm = new Demo();
   }
}

println is overloaded for various types, the one you are invoking is: println对于各种类型都已重载,您要调用的是:

java.io.PrintStream.println(java.lang.Object)

Which looks like this: 看起来像这样:

public void println(Object x) {
  String s = String.valueOf(x);
  synchronized (this) {
    print(s);
    newLine();
  }
}

And String.valueOf looks like this: 而且String.valueOf看起来像这样:

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

So you can see it calls toString() on your object. 因此,您可以看到它在对象上调用了toString() QED 优质教育

调用System.out.println()时,它将尝试在屏幕上打印一些内容(显然)。可以打印的一件事是一个字符串,因此您将方法指定为参数的每个对象都将被“转换”。可以写入输出的内容,因此它调用.toString()方法

The java code to print the Object 用于打印对象的Java代码

 public void println(Object paramObject)
      {
        String str = String.valueOf(paramObject); // Use valueOf method
        synchronized (this) {
          print(str);
          newLine();
        }
      }

valueOf method of String 字符串的valueOf方法

public static String valueOf(Object paramObject)
  {
    return paramObject == null ? "null" : paramObject.toString(); // toString() method is called
  }

The designers of Java decided that they wanted to make it nice and simple to print any object at all, using statements like Java的设计师决定,他们想使使用任何类似的语句使所有对象的打印变得轻松简单。

System.out.println(something);
System.out.print(something);
someOtherPrintWriter.println(something);

without the programmer having to worry too much about what something actually was, so they made lots of versions of those methods. 不必过于担心什么程序员something居然是,让他们做很多的这些方法的版本。 But they couldn't anticipate every possible class that someone might want to print an object of. 但是他们无法预期某人可能要打印其对象的所有可能的类。

But because every class extends Object , either directly or indirectly, all they needed to do was to make any instance of Object printable - which basically meant providing a way to convert any Object to a String . 但是,由于每个类都直接或间接扩展了Object ,因此它们所需要做的就是使Object任何实例都可打印-这基本上意味着提供一种将Object转换为String

They did that by including a toString method in the Object class, and making print and println use it. 他们通过在Object类中包含toString方法,并让printprintln使用它来做到这一点。 Then, if anyone writes a class and needs it objects to be printed in a particular way, all they need to do is override toString , and then print and println will both do what the programmer expects. 然后,如果有人编写了一个类并需要以特定方式打印对象,那么他们要做的就是重写toString ,然后printprintln都将完成程序员的期望。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM