Method Overriding

We sometimes need to change the behaviour of a method in a subclass. The process of doing this is known as overriding and requires us to redeclare the method signature. In Java, we should annotate a method we are overriding by placing the following code on the line above the method:

@Override
This syntax has been used before for implementing a method declared in an interface, however when implementing an interface we are defining the functionality for the first time, but when we override a method in an inherited class we redefine (or, more accurately, extend) its functionality.

Calling the base class function

When overriding a method we often, but not always, still want to use the functionality implemented in that method in the superclass. This can be done by calling super. and the name of the method

All classes extend a base Object

Although when we create a new class, it does not indicate that it extends any other class, all classes in Java implicitly extend a class called Object. Object has some base functionality. Consider the Odometer class from the Classes tutorial. It would be perfectly valid to write the following code:

System.out.println(basicOdometer.toString());
We can do this even though we never declared a method called toString() in the Odometer class. This is because the Object class has a method called toString(). It's default implementation is to print the class name (including the package) followed by the @ symbol and a hash code value for the object, so for the above example the output might be
com.tinyappco.Odometer@61bbe9ba

This is not always particularly helpful, in fact for the Odometer it would be more helpful for debugging purposes if calling toString() on our odometer would provide a representation showing the name of the class along with the miles travelled. We could therefore override the toString() method as shown below:

@Override
public String toString() {
    return "Odometer: "+ Double.toString(totalMilesTravelled);
}
Calling the toString() method on Odometer would now have a different result, and might appear similar to that shown here:
Odometer: 54321.0

Task - Override to String

Override the toString() method for the TripComputer so that it prints the class name, the total mileage, and the trip mileage in a nicely presented manner.

Task - Other classes

Revisit other classes that you have created and override the toString() method so that it returns informative information about the instance of that class when called.