OOP Fundamentals

Classes and objects, the four pillars (encapsulation, abstraction, inheritance, polymorphism), interfaces vs abstract classes, composition over inheritance, and how dynamic dispatch works.

Beginner 4 min readLesson 1 of 24 Interview Q&A

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

PillarOne-linerWhy it matters
EncapsulationHide internal state; expose behaviourObjects protect their invariants; internals can change freely
AbstractionShow what something does, not howCallers depend on simple contracts
InheritanceA class reuses and extends anotherShared behaviour, "is-a" relationships
PolymorphismOne interface, many implementationsCode 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
}

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()); }
}

Interface vs abstract class

InterfaceAbstract class
State (fields)No (constants only in Java)Yes
ConstructorsNoYes
MultipleA class can implement manySingle inheritance (Java, C#)
Default methodsYes (Java 8+)Yes
Use whenDefining 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; }
}

Polymorphism

The same call does different things depending on the object's runtime type:

Java
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
KindMechanismExample
Subtype (runtime)Overriding + dynamic dispatchshape.area()
Ad hoc (compile time)Overloadingprint(int), print(String)
ParametricGenericsList<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.

vptrCircle objectvptr · r=1.0Circle vtablearea → Circle.areaCircle.area()machine code

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.

Inheritance
Java
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.

Composition
Java
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, final fields, frozen dataclasses).
  • equals and hashCode must 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).
Key takeaways
  • 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.
Interview questions
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.