next up previous
Next: Composition (optional) Up: Unit 03 Previous: The class Object

Use of toString in print and println

The predefined class PrintStream contains variants of the methods print and println, which we have used till now, that have a formal parameter of type reference to Object instead of String. These two methods invoke on the parameter of type Object the method toString, and then print the resulting string using the printing method that we have already seen for String. In practice, this allows us to avoid the explicit use of toString in the argument of print and println.

Example:

public class TestToString2 {
  public static void main(String[] args) {
    Person p = new Person("Pippo", "Topolinia");
    System.out.println(p);
    // this is equivalent to System.out.println(p.toString());
  }
}

Note: The methods print and println work correctly when used in this way because of the mechanism of late-binding.


next up previous
Next: Composition (optional) Up: Unit 03 Previous: The class Object