How to use the toString method in Java?

前端 未结 13 906
说谎
说谎 2020-11-21 06:26

Can anybody explain to me the concept of the toString() method, defined in the Object class? How is it used, and what is its purpose?

13条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 06:55

    Whenever you access an Object (not being a String) in a String context then the toString() is called under the covers by the compiler.

    This is why

    Map map = new HashMap();
    System.out.println("map=" + map);
    

    works, and by overriding the standard toString() from Object in your own classes, you can make your objects useful in String contexts too.

    (and consider it a black box! Never, ever use the contents for anything else than presenting to a human)

提交回复
热议问题