toString Methods
Objective #1: Implement a toString method with every class that you design.
- Most classes that are built-in to Java or designed by professional programmers include a method named toString.
- The purpose of the toString method is to allow a client programmer to display the state
of an object. Remember that the state of an object is its set of properties and their values. So if a Bug object had myAge and myWeight properties then the statement
System.out.println(flik.toString());
would display something like
myAge=3 myWeight = 15
The format of the string that is returned by the toString method usually doesn't look very pretty. Usually it is not meant for a customer to see. Class developers add toString methods to classes to help debug their client programs. Normally a toString method is not used in a final version of a program that a customer will see. Instead, programmers use a toString method to inspect the state of an object in order to debug logic errors.
- Here is an example of a toString method implementation that might be found in a Bug class where a Bug object has myAge and myWeight properties
public String toString()
{
return "myAge = " + myAge + " myWeight = " + myWeight;
}
Notice the use of concatenation to "glue" the properties together into one String.
- It is up to the programmer to decide how to format the String that is returned by the toString method. But the String value that is returned by the toString method should be complete and easy-to-read
and interpret by client programmers.
In the example above different programmers could decide to format the information in a variety of ways such as
myAge: 3 myWeight: 15
or
age = 3, weight = 15
- It is a common mistake for programmers to include the actual System.out.println inside of the toString method and to make the toString method void. DO NOT MAKE THAT MISTAKE. It is conventional and
very important to be consistent with other professional programmers and to use the exact method header
public String toString()
when you implement a toString method in any class that you write.
- In a client class, the System.out.println method can be used to invoke the toString method as in
System.out.println(widget.toString());
or
System.out.println(widget);
The latter is preferable since Java automatically invokes an object's toString method when the object variable is a parameter of the println method.