Why is the toString() method being called when I print an object?

前端 未结 5 545
北海茫月
北海茫月 2020-11-27 06:36

I can\'t seem to understand why when I use println method on the quarter object, it returns the value of the toString method. I never called the toString method why am I g

5条回答
  •  情深已故
    2020-11-27 06:45

    On Refering to java docs what i undestand is that,

    When you call PrintStream class print(obj) / println(obj) method then internally it called write method with arguement as String.valueOf(obj) shown below :

    public void print(Object obj) {
        write(String.valueOf(obj));
    }
    

    Now String.valueOf(obj) does the task of calling to String method as shown below :

     /**
     * Returns the string representation of the Object argument.
     *
     * @param   obj   an Object.
     * @return  if the argument is null, then a string equal to
     *          "null"; otherwise, the value of
     *          obj.toString() is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
    }
    

提交回复
热议问题