Given the definition of the Entry class given above, we could evaluate the expression
new Entry("Corky","DH 3104","x 6042")in the DrJava interactions window but the result would not be very informative. When the Java evaluator converts an object to a printable String representation, it uses a method called toString which is defined in class Object. Since every class is a subclass of Object, every class includes the toString method.
Every class inherits a definition of the toString method
from its superclass. The ultimate superclass Object contains a
simple definition for toString that is not very informative: it
returns the String consisting of the class name for this
followed by an "@" sign followed by the address in memory where
the object this is located. Each class below Object in
the superclass hierarchy either relies on the toString method
inherited from its superclass or introduces a new definition for toString() that overrides the definition in its superclass.
Finger Exercise Load your file Entry.java into DrJava
and compile it. Then evaluate
new Entry("Corky","DH 3104","x 6042")
new Entry("Corky","DH 3104","x 6042")
Did you get the results that you expected? Note that each new
operation creates a distinct object.
The Entry class is an immediate subclass of the Object class which defines the toString() method. Hence, invoking toString() on an Entry object uses the definition of toString() inherited from Object unless the class definition for Entry overrides it.
To produce a better printed form for the instances of a class, we must override the inherited definition of toString() with a definition tailored to that class. In the case of the Entry class, we could define toString as follows:
public String toString() {
return "Entry[" + this.name + ", " + this.address + ", "
+ phone + "]";
}
Java requires the public attribute in the header of the toString method because it overrides an inherited method that is public. In Java, every class member has an associated visibility attribute. When an inherited method is overridden, its visibility cannot be reduced. We will discuss this issue in more detail in Section 1.6.4.
Finger Exercise Load your saved program Entry.java into
the Definitions window of DrJava. Add the definition
immediately above to the Entry class and compile the program.
In the Interactions window, evaluate the same print statement as
in the last finger exercise. Is this output more helpful?
Java Design Rule: Redefine (override) the toString()
method for every class that is used to represent data. (Recall that
classes can also be used to group static fields and methods.)