Topic 7 of 30 · Intermediate
OOP: Encapsulation, Inheritance, Polymorphism
The pillars of object-oriented Java.
Concept
Encapsulation: keep fields private and expose behaviour through methods, so the object controls its own state.
Inheritance (extends) lets a subclass reuse and specialise a parent. Java supports single class inheritance; super calls the parent.
Polymorphism: a parent reference can point to a child object, and overridden methods are chosen at run time (dynamic dispatch). Overloading is compile-time polymorphism.
Code (Java 21)
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
}
class Square extends Shape {
private final double s;
Square(double s) { this.s = s; }
@Override double area() { return s * s; }
}
Shape[] shapes = { new Circle(1), new Square(2) };
for (Shape sh : shapes) System.out.println(sh.area()); // runtime dispatchRemember
- Overriding = runtime; overloading = compile time.
- Use @Override to catch mistakes.
- Prefer composition over deep inheritance.
Interview questions
Why doesn't Java support multiple inheritance of classes?
To avoid the diamond problem — ambiguity over which parent's method to inherit. Interfaces provide multiple inheritance of type.
Can static methods be overridden?
No. They can be hidden by a same-signature static method in a subclass, resolved by reference type at compile time.
Lesson test
Take an 8-question test on “OOP: Encapsulation, Inheritance, Polymorphism” — concepts, output prediction, bug spotting and interview questions.