Inheritance
Overview
Inheritance is how classes share code. It creates a Parent-Child relationship (also known as a Superclass and Subclass).
If you have a `Vehicle` class that knows how to start an engine, and you want to make a `Car` class, you shouldn't rewrite the engine code. You just make `Car` inherit from `Vehicle`. The `Car` instantly gets everything the `Vehicle` has. It promotes massive code reuse.
1. The 'extends' Keyword
To make a class inherit from another, we use the word `extends`. It establishes an 'IS-A' relationship (A Car IS-A Vehicle).
2. What gets inherited?
The child class gets all the public and protected variables and methods of the parent. It does NOT get the private ones.
3. Single Inheritance
In Java, a child class can only have ONE parent. You cannot extend multiple classes at the same time.
Syntax
The Dog automatically knows how to eat, even though we didn't write it inside the Dog class.
// The Parent
public class Animal {
public void eat() {
System.out.println("Munch munch...");
}
}
// The Child
public class Dog extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.bark(); // Its own method
myDog.eat(); // Inherited from Animal!
}
}Common Pitfalls
- Overusing inheritance. If you have a chain of 10 parent-child classes, your code becomes fragile and impossible to read.
Interview Tips
- Always mention 'IS-A' relationship. Do not use inheritance just to reuse code if the objects aren't related. A 'Car' IS-A 'Vehicle'. A 'Coffee' IS NOT A 'Mug', so they shouldn't inherit from each other.
Real-World Example
Inheritance is used in UI development. A 'SubmitButton' inherits all the basic drawing logic from a generic 'UIComponent' parent class.
public class UIComponent {
int x, y;
public void drawOnScreen() { /* logic */ }
}
public class Button extends UIComponent {
String text = "Click Me";
// It gets drawOnScreen() for free!
}