How to use the toString method in Java?

前端 未结 13 916
说谎
说谎 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:56

    It may optionally have uses within the context of an application but far more often it is used for debugging purposes. For example, when you hit a breakpoint in an IDE, it's far easier to read a meaningful toString() of objects than it is to inspect their members.

    There is no set requirement for what a toString() method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString() methods are auto-generated in IDEs.

    Relying on particular output from a toString() method or parsing it within a program is a bad idea. Whatever you do, don't go down that route.

提交回复
热议问题