Overriding toString

The Object class provides a toString method, however it isn’t very useful.  It simply prints the name of the class, followed by @ and a hexadecimal representation of the hashCode value.  It is recommended that all classes override the toString method to make the method more useful.

The toString method is called automatically when an instance of the class is

  1. passed to a println or printf method
  2. concatenated with a String object
  3. passed to the assert method

If you’ve overridden the toString method, then creating useful error messages is easier.  Suppose for example we have a class named Pair.  A useful toString method for the Pair class might look like this:

class Pair{
    int x;
    int y;

    ...

    @Override
    public String toString() {
        return "(" + x + "," + y ")";
    }
}

Generating useful error messages is easy since we can simply concatenate an instance of the Pair class with an error message.

System.out.println("Duplicate pair: " + pair1);

It is also recommended that all significant information (within reasonable limits) be included in the String returned by toString.

© 2017 – 2019, Eric. All rights reserved.