OOP/Lesson 2 of 5/6 min read
The Four Pillars
Encapsulation, abstraction, inheritance and polymorphism, with overloading vs overriding, dynamic dispatch and abstract classes vs interfaces.
On this page
The four pillars at a glance
| Pillar | One-line meaning | Mechanism |
|---|---|---|
| Encapsulation | Hide internal state, expose controlled operations | Access modifiers |
| Abstraction | Show what an object does, hide how | Interfaces, abstract classes |
| Inheritance | A class reuses and extends another | extends, : |
| Polymorphism | One interface, many implementations | Overloading, overriding |
Encapsulation
Bundling data with the methods that operate on it, and restricting direct access to the data. The object guards its own invariants.
class Temperature {
private double celsius;
public void setCelsius(double c) {
if (c < -273.15) throw new IllegalArgumentException("below absolute zero");
this.celsius = c;
}
public double getFahrenheit() { return celsius * 9 / 5 + 32; }
}Benefits: invalid states are impossible from outside, internals can change without breaking callers, and debugging is easier because state changes go through one place.
Abstraction
Exposing only essential features and hiding implementation details. A driver uses the steering wheel and pedals without knowing how the engine works. List.add() hides whether it is an array or a linked list.
Encapsulation vs abstraction: abstraction is a design idea (what to expose); encapsulation is the implementation tool (how to hide the rest).
Inheritance
A subclass (child) acquires fields and methods of a superclass (parent) and can add or override behavior. Models an is-a relationship: a Dog is an Animal.
class Animal {
protected String name;
void speak() { System.out.println("..."); }
}
class Dog extends Animal {
@Override
void speak() { System.out.println(name + " says woof"); }
}Types of inheritance
| Type | Shape | Supported in |
|---|---|---|
| Single | A to B | All |
| Multilevel | A to B to C | All |
| Hierarchical | A to B, A to C | All |
| Multiple | A and B to C | C++, Python (Java and C# only via interfaces) |
| Hybrid | Mix of the above | C++, Python |
Diamond Problem
B and C both extend A and override foo(); D extends both B and C. Which foo() does D get?
- Java and C# avoid it by disallowing multiple class inheritance. With default methods in two interfaces, the class must override explicitly.
- C++ uses virtual inheritance to share one
Asubobject. - Python uses the method resolution order (C3 linearization); inspect with
D.__mro__.
Pitfalls of inheritance
- Tight coupling: changes in the parent ripple into every child (fragile base class).
- Deep hierarchies are hard to understand.
- Using inheritance for code reuse when there is no real is-a relationship. Prefer composition (has-a); see advanced OOP.
Polymorphism
"Many forms": the same call behaves differently depending on the type.
Method Overloading
Compile-time (static) polymorphism: same method name, different parameter lists, in the same class.
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }The return type alone cannot distinguish overloads. Python has no true overloading (the last definition wins); use default arguments or functools.singledispatch.
Method Overriding
Runtime (dynamic) polymorphism: a subclass provides its own implementation of a parent method with the same signature.
Animal a = new Dog();
a.speak(); // "woof": decided at runtime by the actual object typeRules (Java): same name and parameters; return type same or covariant (a subtype); access cannot be more restrictive; cannot throw broader checked exceptions; static, final and private methods cannot be overridden.
| Overloading | Overriding | |
|---|---|---|
| Where | Same class | Parent and child |
| Signature | Different parameters | Same parameters |
| Resolved | Compile time | Runtime |
| Also called | Static polymorphism | Dynamic polymorphism |
Dynamic Dispatch
How runtime polymorphism works. In C++ and Java, each class with virtual methods has a vtable (table of function pointers), and each object holds a hidden pointer to its class's vtable. A virtual call looks up the method in the vtable at runtime.
- In Java, all non-static, non-final, non-private methods are virtual by default.
- In C++, only methods marked
virtualare. Forgettingvirtualon a base destructor leaks resources when deleting through a base pointer.
Abstract Class
A class that cannot be instantiated and may contain both implemented and abstract (unimplemented) methods. Subclasses must implement the abstract ones.
abstract class Shape {
abstract double area();
void describe() { System.out.println("Area: " + area()); } // template
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}Interface
A pure contract: a set of method signatures a class promises to implement. A class can implement many interfaces.
interface Payable { void pay(double amount); }
interface Refundable { void refund(String txId); }
class CardPayment implements Payable, Refundable { ... }Since Java 8, interfaces can have default and static methods; since Java 9, private helpers.
Abstract class vs interface
| Abstract class | Interface | |
|---|---|---|
| Instantiable | No | No |
| State (instance fields) | Yes | No (only constants) |
| Constructors | Yes | No |
| Multiple inheritance | No (one parent) | Yes (many interfaces) |
| Methods | Abstract and concrete | Abstract, default, static |
| Relationship | is-a, shared base code | can-do capability |
| Use when | Related classes share code and state | Unrelated classes share a capability |
Quick revision
- Encapsulation hides state behind methods and protects invariants.
- Abstraction exposes what, hides how; encapsulation is the tool that enforces it.
- Inheritance is is-a; beware fragile base classes and prefer composition for reuse.
- Diamond problem: Java forbids multiple class inheritance, C++ uses virtual inheritance, Python uses MRO.
- Overloading: same name, different parameters, compile time. Overriding: same signature in subclass, runtime.
- Dynamic dispatch uses vtables; make C++ base destructors virtual.
- Abstract class shares code and state; interface defines a capability and allows multiple implementation.