OOP Fundamentals
Classes and objects, the four pillars (encapsulation, abstraction, inheritance, polymorphism), interfaces vs abstract classes, composition over inheritance, and how dynamic dispatch works.
Object-oriented programming organises code around objects: bundles of state (fields) and behaviour (methods) that model things in your domain. A class is the blueprint; an object is an instance. Done well, OOP lets you change one part of a system without breaking the others. Done badly, it buries simple logic under hierarchies.
The four pillars
| Pillar | One-liner | Why it matters |
|---|---|---|
| Encapsulation | Hide internal state; expose behaviour | Objects protect their invariants; internals can change freely |
| Abstraction | Show what something does, not how | Callers depend on simple contracts |
| Inheritance | A class reuses and extends another | Shared behaviour, "is-a" relationships |
| Polymorphism | One interface, many implementations | Code works with types that don't exist yet |
Encapsulation
Keep fields private and change state only through methods that enforce invariants. A bank account should never have a negative balance, no matter who calls it.
public class Account {
private long balanceCents; // hidden state
public void deposit(long cents) {
if (cents <= 0) throw new IllegalArgumentException("must be positive");
balanceCents += cents;
}
public void withdraw(long cents) {
if (cents > balanceCents) throw new IllegalStateException("insufficient funds");
balanceCents -= cents;
}
public long balance() { return balanceCents; } // read-only view
}class Account:
def __init__(self):
self._balance_cents = 0 # leading underscore = internal by convention
def deposit(self, cents: int):
if cents <= 0:
raise ValueError("must be positive")
self._balance_cents += cents
def withdraw(self, cents: int):
if cents > self._balance_cents:
raise ValueError("insufficient funds")
self._balance_cents -= cents
@property
def balance(self) -> int: # read-only attribute
return self._balance_centsclass Account {
#balanceCents = 0; // truly private (runtime-enforced)
deposit(cents: number) {
if (cents <= 0) throw new Error("must be positive");
this.#balanceCents += cents;
}
withdraw(cents: number) {
if (cents > this.#balanceCents) throw new Error("insufficient funds");
this.#balanceCents -= cents;
}
get balance() { return this.#balanceCents; }
}Abstraction and interfaces
An interface declares what an object can do, without how. Callers program against the interface, so implementations can be swapped.
interface PaymentGateway {
Receipt charge(String customerId, long cents);
}
class StripeGateway implements PaymentGateway {
public Receipt charge(String customerId, long cents) { /* call Stripe */ return null; }
}
class Checkout {
private final PaymentGateway gateway; // depends on the abstraction
Checkout(PaymentGateway gateway) { this.gateway = gateway; }
void pay(Order o) { gateway.charge(o.customerId(), o.totalCents()); }
}from typing import Protocol
class PaymentGateway(Protocol): # structural interface
def charge(self, customer_id: str, cents: int) -> "Receipt": ...
class StripeGateway:
def charge(self, customer_id: str, cents: int) -> "Receipt":
... # call Stripe
class Checkout:
def __init__(self, gateway: PaymentGateway):
self.gateway = gateway
def pay(self, order):
self.gateway.charge(order.customer_id, order.total_cents)interface PaymentGateway {
charge(customerId: string, cents: number): Promise<Receipt>;
}
class StripeGateway implements PaymentGateway {
async charge(customerId: string, cents: number) { /* call Stripe */ return {} as Receipt; }
}
class Checkout {
constructor(private gateway: PaymentGateway) {}
pay(o: Order) { return this.gateway.charge(o.customerId, o.totalCents); }
}Interface vs abstract class
| Interface | Abstract class | |
|---|---|---|
| State (fields) | No (constants only in Java) | Yes |
| Constructors | No | Yes |
| Multiple | A class can implement many | Single inheritance (Java, C#) |
| Default methods | Yes (Java 8+) | Yes |
| Use when | Defining a capability ("can be compared") | Sharing code and state among closely related classes |
Inheritance
A subclass inherits fields and methods and can override them. Use it only for true "is-a" relationships where the subclass can stand in anywhere the parent is expected (Liskov).
abstract class Shape {
abstract double area();
String describe() { return getClass().getSimpleName() + " with area " + area(); }
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
}
class Rect extends Shape {
private final double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
@Override double area() { return w * h; }
}from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
def describe(self) -> str:
return f"{type(self).__name__} with area {self.area():.2f}"
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return math.pi * self.r ** 2
class Rect(Shape):
def __init__(self, w, h): self.w, self.h = w, h
def area(self): return self.w * self.habstract class Shape {
abstract area(): number;
describe() { return `${this.constructor.name} with area ${this.area().toFixed(2)}`; }
}
class Circle extends Shape {
constructor(private r: number) { super(); }
area() { return Math.PI * this.r ** 2; }
}
class Rect extends Shape {
constructor(private w: number, private h: number) { super(); }
area() { return this.w * this.h; }
}Polymorphism
The same call does different things depending on the object's runtime type:
List<Shape> shapes = List.of(new Circle(1), new Rect(2, 3));
for (Shape s : shapes) System.out.println(s.area()); // Circle.area, then Rect.area| Kind | Mechanism | Example |
|---|---|---|
| Subtype (runtime) | Overriding + dynamic dispatch | shape.area() |
| Ad hoc (compile time) | Overloading | print(int), print(String) |
| Parametric | Generics | List<T> |
| Duck typing | "If it has the method, call it" | Python, JS |
How dynamic dispatch works
In Java and C++, each class has a vtable: a table of pointers to its method implementations. Each object holds a pointer to its class's vtable. A virtual call loads the object's vtable and jumps to the entry for that method — one or two extra memory loads. JITs often inline the call when only one implementation is seen at a call site.
Composition over inheritance
Inheritance couples a subclass tightly to its parent's internals: change the parent and subclasses break (the fragile base class problem). Deep hierarchies also explode combinatorially: FlyingSwimmingDuck, RobotDuck… Composition — an object has collaborators and delegates to them — is usually more flexible.
class Logger { void log(String m) {...} }
class FileLogger extends Logger {...}
class EncryptedFileLogger
extends FileLogger {...}
class CompressedEncryptedFileLogger
extends EncryptedFileLogger {...}Fixed at compile time; one class per combination.
class Logger {
private final Sink sink;
private final List<Transform> transforms;
// log() applies transforms, then sink.write()
}
new Logger(new FileSink(), List.of(
new Compress(), new Encrypt()));Mix and match at runtime.
Inherit for is-a with a stable parent; compose for has-a and for varying behaviour. Many design patterns (Strategy, Decorator, Bridge) are composition techniques.
Other essentials
- Constructors establish invariants; an object should never exist in an invalid state.
- Immutability: objects whose state never changes are thread-safe and easy to reason about (records,
finalfields, frozen dataclasses). equalsandhashCodemust be overridden together; equal objects must have equal hashes, or hash maps break.- Static members belong to the class, not instances; overusing them is procedural code in disguise.
- Cohesion and coupling: a class should do one thing well (high cohesion) and know little about others (low coupling).
- Encapsulation protects invariants; tell objects what to do instead of manipulating their data.
- Program to interfaces; implementations become swappable.
- Inherit only for true is-a relationships; prefer composition for flexibility.
- Polymorphism via dynamic dispatch (vtables) lets one call site handle many types.
- Aim for high cohesion and low coupling.
QWhat is the difference between overloading and overriding?easy
Overloading is several methods with the same name but different parameter lists in the same class, chosen at compile time. Overriding is a subclass providing its own implementation of an inherited method with the same signature, chosen at runtime by dynamic dispatch.
QWhy prefer composition over inheritance?medium
Inheritance creates tight coupling to the parent's implementation (fragile base class), is fixed at compile time, and leads to class explosions when behaviours combine. Composition delegates to interchangeable collaborators, can change at runtime, and keeps classes small. Inheritance is still right for genuine, stable is-a relationships.
QInterface or abstract class?easy
Use an interface to define a capability many unrelated classes can have (and a class can implement many). Use an abstract class when closely related classes share state and implementation. In modern Java, interfaces with default methods cover many former abstract-class uses.