Unit 4 · The Four Pillars in Depth · 10 min
Inheritance
Inheritance lets a new class reuse the fields and methods of an existing class using the keyword `extends`.
Why this matters
It removes duplicate code. Common features go in the parent class; only the differences go in the child.
Real-life analogy
You inherit features from your parents and add your own. A Car is a Vehicle with extra car-specific things.
Syntax
Syntax
class Child extends Parent { }Example
Java
class Person {
String name;
void introduce() {
System.out.println("I am " + name);
}
}
class Student extends Person {
int rollNumber;
void showRoll() {
System.out.println(name + " has roll number " + rollNumber);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.name = "Ananya Rao"; // inherited from Person
s.rollNumber = 12;
s.introduce(); // inherited method
s.showRoll();
}
}Output
I am Ananya Rao Ananya Rao has roll number 12
Step by step
- 1`class Student extends Person` makes Student the child (subclass) of Person.
- 2Student automatically gets the field `name` and the method `introduce()`.
- 3Student adds its own field rollNumber and method showRoll().
- 4This is an IS-A relationship: a Student IS-A Person.
Key points
- extends creates a parent-child relationship
- Types: single, multilevel, hierarchical
- Java does NOT support multiple inheritance of classes (use interfaces instead)
- private members are not directly accessible in the child
Common mistakes
- Trying `class A extends B, C` — not allowed in Java
- Expecting to access a private parent field directly in the child
- Using inheritance where composition (HAS-A) is more suitable
Try it yourself
- Create Vehicle and Car classes using inheritance.
- Build a three-level chain: Person → Employee → Manager.