I see that Most of the times in the DTO object , the toString Method is actaully overridden .
For example :
public class Person implements Serializable {
private String firstName;
private String lastName;
private int age;
/**
* Creates a new instance of Person
*/
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//Overriding toString to be able to print out the object in a readable way
//when it is later read from the file.
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(firstName);
buffer.append("\n");
buffer.append(lastName);
buffer.append("\n");
buffer.append(age);
buffer.append("\n");
return buffer.toString();
}
}
Could anybody please tell me what is the use of doing so ??
It makes the debugger easier to use. In Eclipse (and I believe in nearly every IDE), the debugger shows the output of toString()
on an object by default.
Edit: As other's have pointed out, there are plenty of other uses: logging, display in a GUI element, or anywhere else you need to convert the object to text for display.
The answer is in your code comment. When debugging, you want to be able to print a human readable representation of your object. If you don't override toString
you will most likely have a representation like:
Person@129cfbb
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With