In Java, why would you want to override the ToString method? Let me illustrate this with a simple example.
Define a TEST5 class first. and write its Get,set method.
Package test5;
public class Test5 {
private String name;
Private String sex;
private int No;
public void Show () {
System.out.println ("This is my way of showing!!!! ");
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String Getsex () {
return sex;
}
public void Setsex (String sex) {
This.sex = sex;
}
public int Getno () {
return No;
}
public void Setno (int no) {
This. no = no;
}
}
Then define a class of TEST6 with the main function, as follows:
Package test5;
public class Test6 {
public static void Main (string[] args) {
Class<?> demo= null;
try {
Demo=class.forname ("Test5. Test5 ");
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Test5 test5= new Test5 ();
Test5.setname ("Xiaoming");
Test5.setno (001);
Test5.setsex ("man");
System.out.println (TEST5);
}
}
Running the above program discovery, the results are as follows:
[Email protected]
Obviously this is not the Test5 attribute value we want to get, for the simple reason that ToString in the object class just prints the string directly,
The number is converted into characters and then printed, and the object is directly printed with the hash code of the object. The result above is the hash value of the TEST5.
The ToString method should be overridden if you want to get the individual property values of TEST5. As follows:
Public String toString () {
Return "[" +this.name+ "" +this.sex+ "" +this. no+ "]";
}
Then TEST5 should be written as follows:
Package test5;
public class Test5 {
private String name;
Private String sex;
private int No;
Public String toString () {
Return "[" +this.name+ "" +this.sex+ "" +this. no+ "]";
}
public void Show () {
System.out.println ("This is my way of showing!!!! ");
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String Getsex () {
return sex;
}
public void Setsex (String sex) {
This.sex = sex;
}
public int Getno () {
return No;
}
public void Setno (int no) {
This. no = no;
}
}
The result of running TEST6 again this time is:
[Xiaoming man 1]
OK, this is a place to rewrite tostring!!!
"Java" in Java Why do you want to override the ToString method?