When we need a String representation of an object, we can override the toString() method. However, what are the real benefits and reasons for overriding toString() when we can just define a new method to return the string?
Please see example below:
class One
{
private String name;
public One(String _name)
{
name = _name;
}
@Override public String toString()
{
return name;
}
}
class Two
{
private String name;
public Two(String _name)
{
name = _name;
}
public String printMyClass() //Self-defined to print class details
{
return name;
}
}
In the above example, printMyClass() which is self-defined seemed to does the same thing as toString().
So my question is: Why do we still use toString() ?