Intermediate
Inheritance
📂 Phase 3: Object-Oriented Programming (Days 11–16) · JavaInheritance lets one class acquire the fields and methods of another, enabling code reuse and establishing an "is-a" relationship between classes.
Basic Syntax
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks");
}
}
Dog myDog = new Dog();
myDog.eat(); // inherited from Animal
myDog.bark(); // defined in Dog
Types of Inheritance in Java
- Single: One class extends one parent (Dog extends Animal)
- Multilevel: A chain — Puppy extends Dog extends Animal
- Hierarchical: Multiple classes extend the same parent (Dog and Cat both extend Animal)
Java does not support multiple inheritance with classes (a class extending two parent classes), to avoid the "diamond problem" — but it does allow a class to implement multiple interfaces, which is covered later this phase.
The super Keyword
class Dog extends Animal {
void eat() {
super.eat(); // explicitly calls Animal's eat() method
System.out.println("Dog eats kibble");
}
}
super can also call the parent class's constructor, and must be the first line if used that way:
class Animal {
Animal(String sound) {
System.out.println("Animal makes sound: " + sound);
}
}
class Dog extends Animal {
Dog() {
super("Bark"); // calls Animal's constructor
}
}
Method Overriding
A subclass can provide its own implementation of a method already defined in the parent — this is method overriding, distinct from overloading (same name, different parameters within the same class).
class Animal {
void makeSound() {
System.out.println("Some generic sound");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
Interview tip: Why doesn't Java support multiple class inheritance? Answer: ambiguity when two parent classes have a method with the same signature (the diamond problem) — interfaces avoid this because implementing classes must explicitly provide their own method body.