Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to override toString Method inside DTO

Tags:

java

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 ??

like image 650
Pawan Avatar asked Nov 29 '22 18:11

Pawan


2 Answers

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.

like image 32
3 revs, 2 users 80% Avatar answered Dec 05 '22 11:12

3 revs, 2 users 80%


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
like image 185
Giann Avatar answered Dec 05 '22 13:12

Giann