Inheritance is the OOP concept where a child class inherits properties and behaviors (fields + methods) from a parent (super) class. It allows code reuse, method overriding and forms the base for polymorphism.

Example

class Animal {
    void makeSound() {
        System.out.println("Default sound");
    }
}
 
class Dog extends Animal {
    void bark() {
        System.out.println("Bark");
    }
}
 
Dog dog = new Dog();
dog.makeSound(); // Inherited from Animal class
dog.bark();      // Dog's own method

Types of Inheritance in Java

TypeSupported in Java?Example
Singleβœ…Dog extends Animal
Multilevelβœ…Class A β†’ B β†’ C
Hierarchicalβœ…Cat and Dog extend Animal
Multiple (classes)(use interfaces instead)

Key Concepts

  • Use extends keyword for class inheritance.
  • Constructors are not inherited, but can be called via super().
  • Overriding methods = polymorphism.
  • Can access parent class members with super.

Real-World Analogy

A Car class can inherit from a more generic Vehicle class.

Tip

Be ready to explain:

  • The benefits of inheritance (code reuse, polymorphism),
  • Why Java doesn’t support multiple inheritance with classes (to avoid ambiguity like the diamond problem).

Parent: _OOP Concepts