next up previous
Next: 1.4 The Union and Up: 1.3 Java Class Definitions Previous: 1.3.3 Defining Instance Methods


1.3.4 Printing Objects

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 pane but the result would not be very informative. When the Java evaluator needs to convert 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 @ 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. This definition of toString simply generates the String consisting of the name of the class concatenated with an sign and an identifying serial number for the object.

To produce a better printed form for the instances of a class, we must define a toString method specifically for 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.5.5.


Finger Exercise Load your saved program Entry.java into the Definitions pane of DrJava. Add the definition immediately above to the Entry class and compile the program. In the Interactions pane, 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.)


next up previous
Next: 1.4 The Union and Up: 1.3 Java Class Definitions Previous: 1.3.3 Defining Instance Methods
Corky Cartwright 2003-07-07