Hi I would be really interested to understand how exactly the toString() method works. I have read quite a bit about it, that it returns the string representation of
an object, that the default one can be overridden with @Override etc etc.
Let's have a look at some examples:
@Override // indicates that this method overrides a superclass method
public String toString()
{
return String.format( "%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f",
"commission employee", firstName, lastName,
"social security number", socialSecurityNumber,
"gross sales", grossSales,
"commission rate", commissionRate );
} // end method toString
and it is called in this way
System.out.printf( "\n%s:\n\n%s\n",
"Updated employee information obtained by toString",
employee.toString() );
where employee is an object. firstName
, lastName
etc are all private instance variables of the class
Or anothe similar one:
@Override // indicates that this method overrides a superclass method
public String toString()
{
return String.format( "%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f",
"commission employee", firstName, lastName,
"social security number", socialSecurityNumber,
"gross sales", grossSales,
"commission rate", commissionRate );
} // end method toString
which is called by
System.out.printf( "\n%s:\n\n%s\n",
"Updated employee information obtained by toString", employee );
again, employee is the object.
Now what I don't understand is what is the difference between printing an object this way and printing an object with a normal call to System.out.printf and list the instance
variables? I mean why do I need a toString method for? Maybe in the examples above, since they are taken from large program, I might not see the point of it.