Java Learner logo

Module 6: Inheritance and Polymorphism

Lesson focus

Method Overriding, the `@Override` Annotation, and the `super` Keyword

Learn how a subclass can provide its own specific implementation of a method that is already defined in its superclass.

What is Method Overriding? Method overriding occurs when a subclass provides a specific implementation for a method that is already provided by its superclass. The method in the subclass must have the same name, same parameters, and same return type as the method in the parent class.

The @Override Annotation: This annotation is placed directly above the overridden method in the subclass. It is not required, but it is highly recommended. It tells the compiler that you intend to override a method from the superclass. If you make a mistake (e.g., misspell the method name or change the parameters), the compiler will give you an error, saving you from hard-to-find bugs.

The super Keyword: Inside a subclass, the super keyword is used to refer to its immediate superclass. You can use it to:

  • Call the superclass's constructor: super(arguments) must be the very first line in a subclass constructor.
  • Call a superclass's method: super.methodName() is useful when you want to extend the behavior of the superclass method, not completely replace it. You can call the parent method and then add more functionality.

Overriding vs. Overloading:

  • Overriding: Same method signature, different implementation in a subclass.
  • Overloading: Same method name, different parameters in the same class.

Mini-Exercise: In your Car class that extends Vehicle, override the start() method to print "Car engine started!" instead of the generic message. Use the @Override annotation.

class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound.");
    }
}

class Dog extends Animal {
    @Override // Good practice!
    public void makeSound() {
        System.out.println("The dog barks.");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        super.makeSound(); // Call the parent method first
        System.out.println("The cat meows."); // Then add specific behavior
    }
}

Lesson quiz

What is the main purpose of the `@Override` annotation?

Next lesson →