Inheritance in Java
Inheritance lets a child (sub) class acquire the fields and methods of a parent (super) class using extends. It models an IS-A relationship and promotes code reuse.
class Animal {
void eat() { System.out.println("Eating..."); }
}
class Dog extends Animal {
void bark() { System.out.println("Barking..."); }
}
Dog d = new Dog();
d.eat(); // inherited
d.bark();
Eating...
Barking...
Types of Inheritance
| Type | Structure | Supported with classes? |
|---|---|---|
| Single | A → B | Yes |
| Multilevel | A → B → C | Yes |
| Hierarchical | A → B, A → C | Yes |
| Multiple | A, B → C | No (only through interfaces) |
Why no multiple inheritance?If two parents had the same method, the child wouldn't know which to use (the diamond problem). Java avoids this ambiguity for classes.
The super Keyword
class Vehicle { Vehicle() { System.out.println("Vehicle created"); } }
class Bike extends Vehicle {
Bike() {
super(); // calls parent constructor (implicit anyway)
System.out.println("Bike created");
}
}
new Bike();
Vehicle created
Bike created
Track your progress through the Java course