java toString() returning this

前端 未结 2 539
遇见更好的自我
遇见更好的自我 2021-01-24 06:17

In String toString() method returns this and when i pass it System.out.println() it prints the content of the String. It is c

2条回答
  •  不知归路
    2021-01-24 06:39

    and when i pass it System.out.println() it prints the content of the String

    In fact, when you pass a String to System.out.println you don't go through toString anyway. The System.out refers to a PrintStream object which has a method that accepts Strings immediately:

    public void println(String x)

    Prints a String and then terminate the line.


    The contract of toString is to return a string representation of the object:

    public String toString()

    Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

    Since String happens to be a String it can return itself (this)!

提交回复
热议问题