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.

Java
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

ABSingleABCMultilevelABCHierarchicalABC✗Multiple(only via interfaces)
Types of inheritance (arrows point from child to parent)
TypeStructureSupported with classes?
SingleA → BYes
MultilevelA → B → CYes
HierarchicalA → B, A → CYes
MultipleA, B → CNo (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

Java
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