What is inheritance in OOP?
Inheritance is an OOP feature where a new class reuses the fields and methods of an existing class. The existing class is called the parent or base class, and the new one is called the child or derived class. It promotes code reuse and lets you build a clear hierarchy of related types.
The core idea
Inheritance lets a child class automatically get everything a parent class already has, and then add or change things. Instead of copying code, you extend it. A Dog is an Animal, so Dog can inherit eat and sleep from Animal and simply add bark.
class Animal {
void eat() { System.out.println("eating"); }
void sleep() { System.out.println("sleeping"); }
}
class Dog extends Animal { // Dog inherits from Animal
void bark() { System.out.println("woof"); }
}
Dog d = new Dog();
d.eat(); // inherited
d.bark(); // its own
Common types of inheritance
- Single: one child inherits from one parent.
- Multilevel: a child inherits from a parent that itself inherits from another class.
- Hierarchical: many child classes inherit from one parent.
- Multiple: one class inherits from more than one class, which Java allows only through interfaces.
Why it helps
Inheritance removes duplicate code and creates a natural is a relationship. When shared logic lives in the parent, a fix or improvement there instantly benefits every child class.
Be ready for the follow up on why Java does not support multiple inheritance with classes. The short answer is the diamond problem, where a class could inherit two versions of the same method and the compiler would not know which to use. Java solves this by allowing multiple inheritance only through interfaces.
Common follow up questions
Related interview questions
Want the full OOP guide?
Read every OOP concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the OOP guide All OOP questions