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
Type | Supported 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