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

  
1.4.4 Printing Objects

Given the definition of the Entry class given above, we could try to print an Entry object as follows:

System.out.println(new Entry("Corky","DH 3104","x 6042"));
but the results would not be very informative. When the print method System.out.println is given an object value as input, it uses the instance method toString() to produce a print representation for the object value. Every class inherits a definition of the toString method from its superclass. The ultimate superclass Object contains a simple definition for toString. 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 Define the Entry class in DrJava and compile it. Then evaluate the print statement above in the Interactions window.


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[" + name + ", " + address + ", " + phone + "]";
}

Java requires the public attribute in the header of the toString method because it overrides an inherited method with that 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 Add the definition immediately above to the Entry class in the Definitions window of DrJava and compile it. In the Interactions window, evaluate the same print statement as in the last finger exercise. Is this output more helpful?


next up previous
Next: 1.5 The Union and Up: 1.4 Java Class Definitions Previous: 1.4.3 Defining Instance Methods
Corky Cartwright
2000-01-07