How an object will call toString method implicitly?

后端 未结 5 1104
轮回少年
轮回少年 2020-11-28 09:20

If I am printing an object of the class then it is printing the toString() method implementation even I am not writing the toString() method so wha

5条回答
  •  一整个雨季
    2020-11-28 10:14

    You're not explicitly calling toString(), but implicitly you are:

    See:

    System.out.println(foo); // foo is a non primitive variable
    

    System is a class, with a static field out, of type PrintStream. So you're calling the println(Object) method of a PrintStream.

    It is implemented like this:

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

    As we see, it's calling the String.valueOf(Object) method.
    This is implemented as follows:

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

    And here you see, that toString() is called.

提交回复
热议问题