java toString() returning this

前端 未结 2 540
遇见更好的自我
遇见更好的自我 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:30

    The toString method, defined on Object in Java is responsible for converting the object to a String representation. Since String is already a String, the toString method simply returns itself.

    0 讨论(0)
  • 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)!

    0 讨论(0)
提交回复
热议问题