Method Overriding

A subclass overrides an inherited method to provide behavior for the same contract. The parameter list must match exactly, and the return type must be the same type or a subtype of it.

@Override asks the compiler to verify your intention. A spelling or parameter mistake becomes an error instead of silently creating a different method.

Replace inherited behavior

class Notification {
    String send() {
        return "Sending notification";
    }
}

class PushNotification extends Notification {
    @Override
    String send() {
        return "Sending push notification";
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Notification().send());
        System.out.println(new PushNotification().send());
    }
}

Output:

Sending notification
Sending push notification

Notification and PushNotification answer the same send() call differently.

Overriding is selected by the runtime object's type. Overloading, taught earlier, is selected from argument types at compile time.

Override Dog.sound so it returns Woof.