Lesson 21: Method Overriding and the super keyword
1. Method Overriding
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method signature (name and parameters) must be identical.
This is a core concept that enables Polymorphism (runtime binding).
java public class Car { public void accelerate() { System.out.println("Car accelerates normally."); } }
public class SportsCar extends Car { // Method Overriding: providing a specialized implementation @Override public void accelerate() { System.out.println("SportsCar accelerates rapidly! (Vroom!)"); } }
// Usage: Car myCar = new Car(); SportsCar fastCar = new SportsCar();
myCar.accelerate(); // Output: Car accelerates normally. fastCar.accelerate(); // Output: SportsCar accelerates rapidly! (Vroom!)
@Override Annotation: While optional, it is best practice to use the @Override annotation. It tells the compiler to check if the method is actually overriding a superclass method, catching errors early.
2. The super Keyword
The super keyword is used to refer to the immediate parent class object.
A. Calling Superclass Methods
Allows the subclass to execute the parent's version of an overridden method.
java public class SportsCar extends Car { @Override public void accelerate() { super.accelerate(); // Call the parent's Car.accelerate() System.out.println("Then engages turbo."); } }
B. Calling Superclass Constructors
Used to explicitly call a superclass constructor from the subclass constructor. If not explicitly used, Java automatically inserts super() (calling the no-arg parent constructor) as the first line.
java // Parent public class Person { public Person(String name) { ... } }
// Child public class Employee extends Person { public Employee(String name) { super(name); // Must be the first statement } }