Why override toString method inside DTO

I see that in most cases in the DTO object, the toString method is canceled.

For instance:

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(); } } 

Can someone please tell me what you need to do?

+4
source share
5 answers

The answer is in your code comment. When debugging, you want to be able to print a user-friendly representation of your object. If you do not override toString , you will most likely have a view like:

 Person@129cfbb 
+8
source

This makes it easier to use a debugger. In Eclipse (and I believe in almost every IDE), the debugger shows the default result of toString() on an object.

Change As others have pointed out, there are many other uses: logging, displaying in a GUI element or elsewhere to convert an object to text for display.

+8
source

This means that when printing an object or adding it to another line, instead of the standard java.lang.Object implementation (it will be something like your.package.Person@... ), the correct result (returned by the toString() implementation) will be displayed.

+3
source

There are many uses. Among other things: to display this object in a combobox in the GUI, for debugging, for some unit testing statements ...

+2
source

Override toString to be able to print an object in a readable way when it is later read from a file.

Sorry, could not resist. Seriously, toStrings are valuable for redefinition for any Java class. However, I would bet on DTO, in particular, it is good to have toString, because the object is designed to transmit data. Often this means printing data in a readable format.

0
source

All Articles