toString Method Call in Java [duplicate]

我的未来我决定 提交于 2019-12-03 10:16:01
Room tempRoom = rooms[i];
if (tempRoom != null) {
    System.out.println(tempRoom);
}

You have the above code in your displayRooms() method. It prints tempRoom, which is a reference of Room, and hence it calls toString() method overridden in the Room class.

when you call

System.out.println(tempRoom);

the toString() method of Room is automatically called on tempRoom.

In this line

System.out.println(tempRoom);

this is the same as

 System.out.println(tempRoom.toString());

toString is a special method of the Object class, here is its description:

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.

This method is widely used in those places when an object should be converted to textual representation. When you print an object to PrintStream (System.out in this case), this stream calls toString to convert this object to a string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!