Can anybody explain to me the concept of the toString()
method, defined in the Object
class? How is it used, and what is its purpose?
The toString()
method returns a textual representation of an object. A basic implementation is already included in java.lang.Object
and so because all objects inherit from java.lang.Object
it is guaranteed that every object in Java has this method.
Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString()
method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:
public class Contact {
private String firstName;
private String lastName;
public Contact (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getContact() {
return firstName + " " + lastName;
}
@Override
public String toString() {
return "["+getContact()+"]";
}
}