In Java, all objects have the ToString method;
The ToString method is not defined when the class is created, and the hash value of the object is output when the object is output;
It's just a way for the Sun company to develop Java in order to facilitate string manipulation of all classes.
It is usually just for ease of output:
For example:
Public classtest2{String name; intAge ; PublicString toString () {return"My name is:" +name+ "\ t my age is:" +Age ; } Public Static voidMain (string[] args) {Test2 Myclass=NewTest2 (); Myclass.name= "Xiao Ming"; Myclass.age= 20; System.out.println (Myclass); //call the object's ToString method by default when using the object name directlySystem.out.println (Myclass.tostring ());//To call the string method manually }}
Operation Result:
If the ToString method is not defined in the class, the hash value of the object is output when the above case is called, as shown in the following case:
Public classtest2{String name; intAge ; /*Public String toString () {return "My name is:" +name+ "\ t my age is:" +age; }*/ Public Static voidMain (string[] args) {Test2 Myclass=NewTest2 (); Myclass.name= "Xiao Ming"; Myclass.age= 20; System.out.println (Myclass); //call the object's ToString method by default when using the object name directlySystem.out.println (Myclass.tostring ());//call the string method manually even if the ToString method is not defined, it can be called because all objects have the ToString method by default }}
Operation Result:
JAVA tostring Method