Why the following code segment auto calls toString() method?

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:

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:

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

So you can see it calls toString() on your object. QED

其他提示

The designers of Java decided that they wanted to make it nice and simple to print any object at all, using statements like

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. 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.

They did that by including a toString method in the Object class, and making print and println use it. 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.

when System.out.println() is called, it tries to print something to the screen (obviously) The one thing that can be printed is a string, so every object that you give the method as parameter is going to be 'converted' to something that can be written to the output, so it calls the .toString() method

The java code to print the Object

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

valueOf method of String

public static String valueOf(Object paramObject)
  {
    return paramObject == null ? "null" : paramObject.toString(); // toString() method is called
  }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top