在實作類別的時候,最好覆寫toString
,如果不覆寫toString
,把物件印出來的時候,會是class name + @ + hash code的十六進位,這串字串對開發人員來說是沒有意義的,以下面的範例來說,Person
這個類別執行時,印出來會是PersonForToString@2a139a55
,這對使用者並沒有幫助。
class PersonForToString {
private String name;
private int age;
public PersonForToString(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
PersonForToString person = new PersonForToString("Lucky", 10);
System.out.println("Person: " + person); //PersonForToString@2a139a55
}
}
但如果有覆寫,在執行System.out.println
或System.out.print
印出Person
時,會自動呼叫toString
,這時候就會印出在toString
實作的內容。另外,特別提醒,覆寫toString
時最好加上註解,如果這個類別是很多人在使用,加上註解可以幫助大家更好理解內容,這樣從toString
取得字串,並且要parse的時候比較容易理解格式。
class PersonForToString {
private String name;
private int age;
public PersonForToString(String name, int age) {
this.name = name;
this.age = age;
}
/**
* Overridden toString() method to provide a string representation of the object.
*
* @return A string representation of the PersonForToString object.
* Format: Person{name='name', age=age}
* Example: Person{name='Lucky', age=10}
* The string includes the class name 'Person' followed by curly braces
* enclosing the name and age properties of the person, with the name
* in single quotes and the properties separated by a comma.
*/
@Override public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public static void main(String[] args) {
PersonForToString person = new PersonForToString("Lucky", 10);
System.out.println("Person: " + person);
}
}