next up previous
Next: Use of toString() in Up: Unit 03 Previous: Example for the design

The toString() method

The toString() method is a method defined for all objects, independently of the class to which they belong, and even if we do not define it explicitly. The reason for this is that the toString() method is defined for the class Object, and hence is inherited by all Java classes (we will discuss inheritance in more detail in Unit 8).

The toString() method has the following header:

public String toString()

This method is used to transform an object into a String. Typically, it is used to construct a string containing the information on an object that can be printed, and we can redefine it for a certain class. If we do not redefine it, the toString() method of the class Object is used (which prints a system code for the object).

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: Example for the design