2.4 The extends and super Keywords
How Java uses the extends and super keywords to connect subclasses with their parent classes and reuse behavior cleanly.
The extends keyword
The extends keyword indicates that you are creating a new class that derives from an existing class. In practice it means "to increase functionality" by reusing the parent's fields and methods and then adding more.
class Subclass extends Superclass {
// New methods and fields added here
}The subclass automatically inherits all accessible members of the superclass while still being free to define its own behavior.
The super keyword
The super keyword is a reference used from a subclass to talk to its immediate parent class object. It is commonly used in three contexts:
1. super.variable
Used to access a variable in the parent class that has been shadowed by a variable with the same name in the subclass.
class Vehicle { int maxSpeed = 120; }
class Car extends Vehicle {
int maxSpeed = 180;
void display() {
System.out.println("Parent Speed: " + super.maxSpeed); // 120
}
}2. super.method()
Used to invoke the parent class version of an overridden method.
class Car extends Vehicle {
void display() {
super.display(); // Calls parent's display method
System.out.println("Child logic here");
}
}3. super()
Used to call the parent class constructor from the subclass constructor. This must be the first statement in the subclass constructor.
class B extends ParentClass {
B(int val) {
super(val); // Passes value to Parent constructor
}
}Shadowing vs Overriding
Shadowing (Fields)
When a subclass declares a field with the same name as the superclass, the parent's field is hidden. It still exists but must be accessed viasuper.
Overriding (Methods)
When a subclass provides a specific implementation for a method already present in the parent class. This enables run-time polymorphism.