Override Methods: toString() and equals()

Any subclass can override a parent class method. That means replacing the parent class method with a custom method that is more specific to the subclass.

Two common examples are shown below.

1) Object.toString()

If you have a custom object type (class), you can change the way it displays when it is converted to a string. By default, if you print an object, it shows a memory address:

Let’s take a class called “Car” that stores car objects.

public class Car {
    String make;
    String model;
    int year;

    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }
}

Now we create a Car object in the main() method of another class and print it:

public class CreateCar {
    public static void main(String[] args) {
        Car myCar = new Car("Ford", "Focus", 2015);
        System.out.println(myCar);
    }
}

The output of this program is a memory address of the Car object myCar:

Car@4554617c

To make this display in a more helpful way, override the toString() method of the Car class. This code goes inside the class, but not inside another method:

@Override
public String toString() {
    return year+" "+make+" "+ model;
}

The “@Override” is a note that lets the programmer and the Java compiler know that this is overriding a parent class method of the same name.