next up previous
Next: Use of toString in Up: Unit 03 Previous: Class hierarchy

The class Object

All classes defined in Java are subclasses of the predefined class Object, even if this is not indicated explicitly.

This means that all classes inherit from Object several standard methods, such as equals, clone, and toString. In this course we will consider only the toString method, which has the following header:

public String toString()

This method is used to transform an object in a String. Typically, it is used to construct a string containing the information on an object that can be printed. If we do not redefine (i.e., override) it, what is used is the toString method of the class Object (which prints a system code for the object), or the toString method in the nearest superclass of the hierarchy that redefines it.

Example:

public class TestToString {
  public static void main(String[] args) {
    Person p = new Person("Pippo", "Topolinia");
    System.out.println(p.toString());
  }
}

This program is executed without errors and prints a string on the screen, for example "Person@601bb1", which corresponds to a code defined by the method toString of Object.

We can redefine the method toString in the class Person in such a way that it returns the name of the person.

public class Person {
  ...
  public String toString() {
    return name;
  }
  ...
}
Now, the same program TestToString prints "Pippo".


next up previous
Next: Use of toString in Up: Unit 03 Previous: Class hierarchy