How an object will call toString method implicitly?

后端 未结 5 1130
轮回少年
轮回少年 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:07

    Every object in Java IS-A(n) Object as well. Hence, if a toString() implementation has not been provided by a class the default Object.toString() gets invoked automatically.

    Object.toString()'s default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.

    even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?

    toString() is one of the few methods (like equals(), hashCode() etc.) that gets called implicitly under certain programmatic situations like (just naming a few)

    • printing an object using println()
    • printing a Collection of objects (toString() is invoked on all the elements)
    • concatenation with a String (like strObj = "My obj as string is " + myObj;)

提交回复
热议问题