OOP: Inheritance & Overriding
Inheritance allows a new class (subclass) to inherit fields and behaviors from an existing class (superclass). This promotes reuse and establishes hierarchical relationships.
1 Extends & The super Keyword
Inheritance uses the **extends** keyword. A subclass automatically inherits all public/protected methods and fields. To work with parent assets:
- `super()`: Invokes the parent class's constructor. This must be the very first line inside the subclass constructor.
- `super.method()`: Invokes a parent method that has been overridden in the child subclass.
2 Method Overriding & Overriding Rules
**Method Overriding** occurs when a subclass provides a specific implementation for a method already defined in its parent class. Overridden methods must match the parent method name, return type, and parameters exactly. It is best practice to label them with the `@Override` annotation, which tells the compiler to check validation rules.
Java — Inheritance & Super
▶ Run Code
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void makeNoise() {
System.out.println("Some general animal sound.");
}
}
// Subclass inheriting from Animal
class Dog extends Animal {
Dog(String name) {
super(name); // Calling the superclass constructor
}
@Override
void makeNoise() {
System.out.println(name + " says: Woof! Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.makeNoise(); // Invokes child overridden method
}
}
3 Code Challenge
Challenge: Create a superclass called `Vehicle` with a field `brand` and constructor. Add a method `startEngine()` printing "Engine started". Create a subclass `Truck` that extends `Vehicle`. Override `startEngine()` to print "Diesel engine roar!". Instantiate `Truck`, verify super calls, and print details.