On this page

OOP Concepts in Depth & UML Class Diagrams

Most engineers can recite "encapsulation, inheritance, polymorphism, abstraction". Far fewer can say what actually happens when shape.area() is called on a Shape reference, why a Java constructor calling an overridable method can see a null field, why Parent p = new Child(); p.staticMethod() runs the parent's code, or why java.util.Stack is a textbook Liskov violation. Those are exactly the questions that separate a strong OOP interview from a weak one — and exactly the knowledge you need to read and draw a UML class diagram in a low-level design round without hesitating over which arrowhead means what.

This lesson is the mechanics and notation companion to Object-Oriented Programming, which covers the four pillars, SOLID, design-pattern overviews, anti-patterns and OOP in five languages. Read that first if the pillars are new to you. Here we go underneath: how dispatch is implemented, how objects are born, copied and die, how languages differ in the details that bite, and how to express a design in UML.

Where this fits

After this lesson, apply it: SOLID Principles for design rules, Design Patterns for reusable structures, and the LLD interview problems — Parking Lot, Library Management and friends — where you will draw the diagrams from Part 2.


Part 1 — OOP Mechanics

Polymorphism, precisely

"Polymorphism" means one name, many behaviours. There are several distinct kinds, and interviewers often mean a specific one:

KindAlso calledResolvedExample
Ad-hocOverloadingCompile timeprint(int), print(String)
Subtype (inclusion)Overriding, runtime polymorphismRun timeShape s = new Circle(); s.area()
ParametricGenerics, templatesCompile time (C++ templates, Rust) or erased (Java)List<T>, std::vector<T>
CoercionImplicit conversionCompile timedouble d = 3;
Structural / duck typing—Compile time (TypeScript, Go interfaces) or run time (Python)"anything with a quack() method"

When someone says "compile-time vs run-time polymorphism" they almost always mean overloading vs overriding.

Overloading vs overriding

OverloadingOverriding
WhatSame name, different parameter lists, usually in the same classSubclass redefines an inherited method with the same signature
Decided byThe static (declared) types of the argumentsThe dynamic (runtime) type of the receiver object
WhenCompile timeRun time
Return typeMay differ (but cannot be the only difference)Same, or covariant (a subtype)
AccessAnyCannot be more restrictive than the overridden method
Exceptions (Java)AnyCannot throw broader checked exceptions
Applies to static methods?YesNo — static methods are hidden, not overridden
Keyword—@Override (Java, annotation), override (C#, C++11, Kotlin, TS 4.3+)

The trap is that the two mechanisms combine: overload resolution uses static types, then overriding dispatches on the receiver's dynamic type. Predict this output:

class Printer {
    void print(Object o) { System.out.println("Printer.Object"); }
    void print(String s) { System.out.println("Printer.String"); }
}

class FancyPrinter extends Printer {
    @Override void print(Object o) { System.out.println("Fancy.Object"); }
    @Override void print(String s) { System.out.println("Fancy.String"); }
}

public class Main {
    public static void main(String[] args) {
        Printer p = new FancyPrinter();
        Object x = "hello";       // static type Object, dynamic type String
        p.print(x);               // ?
        p.print("hello");         // ?
        p.print((String) x);      // ?
    }
}

Output:

Fancy.Object
Fancy.String
Fancy.String

Step by step for p.print(x):

  1. Compile time — pick the overload. The compiler sees p : Printer and x : Object. Of Printer's methods, only print(Object) applies to an Object argument. The call is bound to the signature print(Object).
  2. Run time — pick the override. The receiver is actually a FancyPrinter, so its print(Object) runs.

The string-ness of x is never consulted. Java, C#, C++ and TypeScript are all single dispatch: only the receiver's runtime type selects code. If you need behaviour chosen by the runtime types of two objects (collision of Asteroid with Spaceship), you use the Visitor pattern — two single dispatches chained ("double dispatch"); see Behavioral Patterns. Languages with multiple dispatch (Julia, Common Lisp CLOS, C# dynamic) select on all argument types at run time.

Overload resolution order (Java)

When several overloads could apply, Java picks in three phases, and stops at the first phase that finds a match:

  1. Exact match or widening primitive conversion, no boxing, no varargs (int → long is allowed).
  2. Allow boxing and unboxing (int → Integer).
  3. Allow varargs.

Within a phase, the most specific method wins. So:

static void f(long x)      { System.out.println("long"); }
static void f(Integer x)   { System.out.println("Integer"); }
static void f(int... x)    { System.out.println("varargs"); }

f(5);   // "long"   -- widening beats boxing beats varargs

And f(null) with overloads f(Object) and f(String) prints the String version — String is more specific than Object. Add f(Integer) as well and f(null) is a compile error: ambiguous.

Static vs dynamic dispatch, early vs late binding

  • Static dispatch / early binding — the exact function to call is fixed at compile (or link) time. The compiler emits call Foo::bar directly, and can inline it.
  • Dynamic dispatch / late binding — the function is looked up at run time from the object. The compiler emits an indirect call through a table or a lookup.
LanguageDefault for instance methodsOpt-in / opt-out
C++Staticvirtual makes a method dynamically dispatched
C#Staticvirtual / abstract / override; sealed stops further overriding
JavaDynamicfinal, private and static methods are statically bound
KotlinDynamic but final by defaultopen to allow overriding
Python, Ruby, JavaScriptDynamic (attribute lookup at call time)—
SwiftDynamic for classesfinal, struct methods are static
GoStatic for concrete typesInterface values dispatch dynamically through an itab
RustStatic (monomorphised generics)dyn Trait gives a vtable

"Late binding" sometimes has a stronger meaning — name lookup at run time (Python, Smalltalk, Objective-C message sends) — versus the C++ and Java form where the slot is known at compile time and only its contents vary. Both are "dynamic", but the C++ form is a couple of loads, while a Python method call involves dictionary lookups along the MRO (cached by the interpreter).

How vtables work

C++, Java (in HotSpot), C#, Swift and Rust's dyn Trait all implement subtype polymorphism with virtual method tables. The model is the same everywhere; the details here follow the Itanium C++ ABI used by GCC and Clang on Linux and macOS.

struct Shape {
    virtual ~Shape() = default;
    virtual double area() const = 0;
    virtual const char* name() const { return "shape"; }
    int id = 0;
};

struct Circle : Shape {
    double r;
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
    // name() inherited
};

struct Square : Shape {
    double side;
    explicit Square(double s) : side(s) {}
    double area() const override { return side * side; }
    const char* name() const override { return "square"; }
};
  1. The compiler gives every polymorphic class (one with at least one virtual function) a vtable: a static, read-only array of function pointers, one slot per virtual function, in declaration order. Derived classes copy their base's layout and replace the slots they override, appending slots for new virtuals.
  2. Every object of a polymorphic class gets a hidden pointer, the vptr, usually at offset 0, pointing at its class's vtable.
  3. A virtual call s->area() compiles to: load the vptr from the object, load slot k from the vtable, call through it.

Memory picture for Shape* a = new Circle(2.0); Shape* b = new Square(3.0);:

 heap: Circle object                 .rodata: vtable for Circle
 +-----------------------+          +---------------------------------+
 | vptr  ----------------+--------->| [0] Circle::~Circle()           |
 | id    = 0   (Shape)   |          | [1] Circle::~Circle() (deleting)|
 | (4 bytes padding)     |          | [2] Circle::area()              |
 | r     = 2.0 (Circle)  |          | [3] Shape::name()   <- inherited|
 +-----------------------+          +---------------------------------+
                                     (preceded by offset-to-top and a
                                      pointer to Circle's RTTI typeinfo)

 heap: Square object                 .rodata: vtable for Square
 +-----------------------+          +---------------------------------+
 | vptr  ----------------+--------->| [0] Square::~Square()           |
 | id    = 0             |          | [1] Square::~Square() (deleting)|
 | side  = 3.0           |          | [2] Square::area()              |
 +-----------------------+          | [3] Square::name()  <- override |
                                    +---------------------------------+

(The Itanium ABI emits two destructor entries per class: the "complete object" destructor and the "deleting" destructor that also frees memory.)

flowchart LR
    A["Shape* a"] --> OBJ["Circle object: vptr, id, r"]
    OBJ -->|"vptr"| VT["Circle vtable"]
    VT -->|"slot 2"| F1["Circle::area"]
    VT -->|"slot 3"| F2["Shape::name"]

The call a->area() becomes, roughly:

mov   rax, [rdi]        ; rdi = a; load vptr
call  [rax + 16]        ; slot 2 (8 bytes per slot) -> Circle::area

Consequences you can be asked about:

FactWhy
sizeof an empty class is 1; add one virtual function and it becomes 8 (on 64-bit)The vptr. (1 because distinct objects need distinct addresses)
One vtable per class, one vptr per objectVtables are shared, read-only data
A virtual call costs ~2 loads + an indirect branchUsually cheap when the branch predictor guesses right; the real cost is that it blocks inlining
final / sealed / devirtualisationIf the compiler or JIT can prove the dynamic type, it calls directly and can inline. HotSpot does this speculatively with inline caches, deoptimising if a new subclass appears
Constructors cannot be virtualThere is no object, and so no vptr, until the constructor runs
Destructors should be virtual in a polymorphic basedelete basePtr on a non-virtual destructor calls only ~Base — undefined behaviour, leaks
Virtual call in a C++ constructor calls the base versionDuring Shape's constructor the vptr points at Shape's vtable; it is updated as each derived constructor starts
Multiple inheritance needs multiple vptrsEach non-first base subobject has its own vptr; calls through it go via a thunk that adjusts this

The constructor-calls-virtual trap: C++ vs Java

struct Base {
    Base() { hello(); }
    virtual void hello() { std::puts("Base::hello"); }
};
struct Derived : Base {
    std::string name = "derived";
    void hello() override { std::printf("Derived::hello %s\n", name.c_str()); }
};
int main() { Derived d; }   // prints "Base::hello"
class Base {
    Base() { hello(); }
    void hello() { System.out.println("Base.hello"); }
}
class Derived extends Base {
    private String name = "derived";
    @Override void hello() { System.out.println("Derived.hello " + name); }
}
// new Derived() prints "Derived.hello null"

C++ is conservative: while Base is being constructed the object is a Base, so the call does not dispatch to Derived. Java dispatches to the override immediately — but Derived's field initialisers have not run yet, so name is null. C# behaves like Java. Effective Java item 19: constructors must not invoke overridable methods.

How other languages do it

  • Java (HotSpot): each class has a vtable for class methods and itables for interface methods. Interface calls are slightly costlier (search for the itable), but inline caches make monomorphic call sites as cheap as direct calls.
  • Go: an interface value is a pair (itab pointer, data pointer). The itab is built lazily per (interface, concrete type) pair and holds the method pointers. There is no inheritance, so no vtable on the struct itself.
  • Rust: &dyn Trait is a fat pointer (data pointer, vtable pointer). The object has no vptr; you only pay for dynamic dispatch where you ask for it.
  • Python: a method call looks up the attribute on the instance __dict__, then the class and its MRO. CPython caches lookups per type and, since 3.11, specialises call sites.

Abstract class vs interface

Both describe a type you cannot instantiate directly. The differences are partly conceptual and partly language-specific.

Conceptually: an abstract class is an incomplete implementation — "a Vehicle is something with an engine and these shared behaviours, subclasses fill in the rest". An interface is a capability contract — "anything that is Comparable can be sorted". A class has one parent but many capabilities.

FeatureJava abstract classJava interface (8+)C# interface (8+)TypeScript interfaceC++
Instance fieldsYesNo (only public static final constants)No (static fields allowed in C# 8+)Property declarations onlyAbstract base class can have anything
ConstructorsYesNoNoNoYes
Method bodiesYesdefault, static, and private (9+) methodsDefault implementations, static, privateNo — declarations onlyPure virtual = 0 (may still have a body)
Multiple inheritanceOne superclassA class implements manyManyimplements many; interfaces can extends manyMultiple inheritance of classes
Member accessAnyMethods implicitly publicAny access since C# 8PublicAny
Exists at run timeYesYesYesNo — erased (structural, compile-time only)Yes
State in hierarchyShared, protected stateNoneNoneNoneYes

Key language notes:

  • Java 8 default methods let interfaces evolve without breaking implementors (Collection.stream(), Iterable.forEach()). They are not state: an interface still cannot have instance fields.
  • C# 8 default interface members exist for the same reason, but a default member is only callable through the interface type, not through the class reference.
  • TypeScript interfaces are purely structural — any object with the right shape satisfies them, no implements required, and they vanish from the compiled JavaScript. You cannot do x instanceof MyInterface. Abstract classes, by contrast, compile to real JavaScript classes and support instanceof.
  • C++ has no interface keyword. An "interface" is a class with only pure virtual functions and a virtual destructor. Multiple inheritance from such classes is safe because they carry no state.

When to use which:

Choose an abstract class whenChoose an interface when
Subclasses share real state and codeUnrelated classes need a common capability
You need constructors or protected membersYou need multiple "inheritance" of type
The hierarchy is a genuine is-a familyYou want to swap implementations (DI, mocking)
You want to provide a Template Method skeletonYou are designing an API that third parties implement

A very common mature design: an interface for the type, plus an abstract skeletal implementation (List + AbstractList, Collection + AbstractCollection) that implementors may extend for convenience.

Object lifecycle: constructors, destructors, finalizers

Every object goes through allocation, initialisation, use, cleanup and deallocation. Languages differ wildly in who controls the last two.

stateDiagram-v2
    [*] --> Allocated : new or stack frame
    Allocated --> Initialised : constructor chain runs
    Initialised --> InUse
    InUse --> Unreachable : last reference dropped
    InUse --> Destroyed : scope exit or delete in C++
    Unreachable --> Finalised : GC may run finalizer
    Finalised --> Reclaimed
    Unreachable --> Reclaimed: "no finalizer"
    Destroyed --> [*]
    Reclaimed --> [*]

Construction order

For class C extends B extends A, in both C++ and Java:

  1. Memory is allocated (zeroed in Java).
  2. A's constructor runs completely (including A's field initialisers), then B's, then C's — base first.
  3. Within each level: C++ initialises base subobjects, then members in declaration order (not the order in the initialiser list — compilers warn with -Wreorder), then runs the constructor body. Java runs field initialisers and instance initialiser blocks in textual order, then the rest of the constructor body.

Destruction (C++) runs in exactly the reverse order: derived destructor body, derived members in reverse declaration order, then base destructors.

Java class initialisation (static fields and static {} blocks) happens once, the first time the class is actively used, and also base-first.

class A {
    static { System.out.println("1 A static"); }
    { System.out.println("3 A instance init"); }
    A() { System.out.println("4 A ctor"); }
}
class B extends A {
    static { System.out.println("2 B static"); }
    { System.out.println("5 B instance init"); }
    B() { System.out.println("6 B ctor"); }
}
// new B(); new B();  -> 1 2 3 4 5 6, then 3 4 5 6 (statics only once)

Constructor chaining: this(...) and super(...)

  • this(...) calls another constructor of the same class; super(...) calls a superclass constructor.
  • In Java a constructor that calls neither implicitly calls super(). If the superclass has no no-arg constructor, that is a compile error.
  • Historically this(...)/super(...) had to be the first statement. Java 25 finalised flexible constructor bodies (JEP 513): statements that do not touch this may now come before super(...) — useful for validating arguments before delegating.
  • C++ uses the member initialiser list: Circle(double r) : Shape("circle"), r_(r) {}; C++11 added delegating constructors Circle() : Circle(1.0) {}.
  • Python calls super().__init__(...) explicitly — forget it and the base's state is never set up.

this (C++/Java/C#/TS) or self (Python, Rust) is the receiver; in C++ it is a pointer, in Java a reference. Passing this out of a constructor ("escaping this" — registering a listener, starting a thread) exposes a half-constructed object to other threads and is a classic concurrency bug.

super.method() invokes the parent's implementation, bypassing dynamic dispatch for that one call. Python's super() is subtler: it means "the next class in the MRO", which in a diamond may be a sibling, not the parent.

Destructors, RAII, finalizers

LanguageDeterministic cleanupNon-deterministic hookNotes
C++Destructor, runs at scope exit or delete—RAII: resources owned by objects, released in destructors. std::unique_ptr, std::lock_guard
RustDrop::drop at scope end—Ownership makes RAII the only model
Javatry-with-resources + AutoCloseablefinalize() — deprecated (Java 9), deprecated for removal (Java 18, JEP 421); use java.lang.ref.Cleaner as a safety netFinalizers may never run, run on an unknown thread, resurrect objects, and slow GC
C#using + IDisposable (the Dispose pattern)Finalizer ~Foo()Call GC.SuppressFinalize(this) in Dispose
Pythonwith + context managers__del__CPython refcounting usually runs __del__ promptly, but reference cycles and other interpreters make it unreliable
JavaScriptusing declarations with Symbol.dispose (explicit resource management, shipping in modern engines and TypeScript 5.2+)FinalizationRegistryFinalisation callbacks are best-effort only
Godefer f.Close()runtime.SetFinalizer (and runtime.AddCleanup in Go 1.24+)Same caveats as Java

Rule: never rely on a GC-driven hook to release a scarce resource (file descriptor, socket, lock, DB connection). Use the deterministic construct and treat the finalizer/cleaner only as a leak detector.

try (var conn = dataSource.getConnection();
     var stmt = conn.prepareStatement("SELECT 1")) {
    stmt.execute();
}   // stmt.close() then conn.close(), even on exception -- reverse order of declaration

Copy semantics: shallow vs deep

A shallow copy duplicates the object's fields; reference fields still point at the same nested objects. A deep copy recursively duplicates everything reachable, so the copy shares nothing mutable with the original.

flowchart LR
    subgraph Shallow["Shallow copy"]
        O1["original: name, tags"] --> L1["tags list"]
        C1["copy: name, tags"] --> L1
    end
    subgraph Deep["Deep copy"]
        O2["original: name, tags"] --> L2["tags list"]
        C2["copy: name, tags"] --> L3["new tags list"]
    end
import copy

class Team:
    def __init__(self, name, members):
        self.name, self.members = name, members

a = Team("core", ["ana", "bo"])
s = copy.copy(a)        # shallow
d = copy.deepcopy(a)    # deep

a.members.append("cy")
print(s.members)        # ['ana', 'bo', 'cy']  -- shares the list
print(d.members)        # ['ana', 'bo']

In JavaScript, { ...obj }, Object.assign and Array.from are shallow; structuredClone(obj) is deep (but drops functions and class prototypes).

C++: copy constructors and the rule of three / five / zero

C++ copies by value by default. The compiler-generated copy constructor copies members one by one — which is a shallow copy if a member is a raw pointer, and leads straight to a double free:

class Buffer {
    size_t n_;
    int*   data_;
public:
    explicit Buffer(size_t n) : n_(n), data_(new int[n]{}) {}
    ~Buffer() { delete[] data_; }

    // Rule of three: if you need a destructor, you need these too
    Buffer(const Buffer& o) : n_(o.n_), data_(new int[o.n_]) {          // deep copy
        std::copy(o.data_, o.data_ + n_, data_);
    }
    Buffer& operator=(Buffer o) noexcept {                                // copy-and-swap
        std::swap(n_, o.n_); std::swap(data_, o.data_); return *this;
    }
    // Rule of five adds the move operations: steal the pointer, leave o empty
    Buffer(Buffer&& o) noexcept : n_(o.n_), data_(o.data_) { o.n_ = 0; o.data_ = nullptr; }
};
  • Rule of three: destructor, copy constructor, copy assignment — define all or none.
  • Rule of five: add move constructor and move assignment (C++11).
  • Rule of zero: best of all — hold resources in std::vector, std::unique_ptr, std::string and write none of them.

Java: clone() is broken; prefer copy constructors

Object.clone() is protected, returns Object, makes a shallow field-by-field copy, only works if the class implements the marker interface Cloneable (which has no methods), throws a checked CloneNotSupportedException, bypasses constructors, and cannot assign final fields. Effective Java's verdict: prefer a copy constructor or static copy factory.

public final class Order {
    private final String id;
    private final List<LineItem> items;

    public Order(Order other) {                         // copy constructor
        this.id = other.id;                             // immutable: share
        this.items = new ArrayList<>(other.items.size());
        for (LineItem li : other.items) this.items.add(new LineItem(li));   // deep
    }
}

The Prototype pattern (Creational Patterns) is the design-level name for "create objects by copying a template".

Immutability makes copying a non-question

If an object and everything it references is immutable, a shallow copy is a deep copy — and you rarely need a copy at all; just share the reference. That is why String, LocalDate and records are so pleasant.

Static members

A static (class-level) member belongs to the class, not to any instance.

  • Static fields have one copy per class — strictly, in Java, one per class per class loader, which matters in app servers and plugin systems.
  • Static methods have no this; they cannot touch instance members directly and are not polymorphic.
  • In Java and C#, static methods can be called through an instance reference (obj.staticMethod()), which compiles to a call on the reference's declared type — legal, misleading, and a lint warning.
  • C++ static data members need one out-of-class definition (or inline static since C++17).
  • Python distinguishes @staticmethod (no implicit argument) from @classmethod (receives the class cls, so it is polymorphic over subclasses — useful for alternative constructors).
  • Static mutable state is global state: it hides dependencies, breaks test isolation and needs synchronisation. Static constants and pure utility functions are fine.

Method hiding vs overriding

Overriding replaces behaviour for dynamic dispatch. Hiding declares a new member with the same name that merely shadows the parent's when accessed through the subclass's static type.

class Parent {
    static String who()  { return "Parent.static"; }
    String name = "Parent.field";
    String inst()        { return "Parent.inst"; }
}
class Child extends Parent {
    static String who()  { return "Child.static"; }     // HIDES Parent.who
    String name = "Child.field";                        // HIDES Parent.name
    @Override String inst() { return "Child.inst"; }    // OVERRIDES
}

Parent p = new Child();
p.who();    // "Parent.static" -- static methods bind to the declared type
p.name;     // "Parent.field"  -- fields are never polymorphic
p.inst();   // "Child.inst"    -- only instance methods dispatch dynamically

C# makes hiding explicit with the new modifier:

class Animal { public virtual string Speak() => "..."; public string Kind() => "animal"; }
class Dog : Animal {
    public override string Speak() => "Woof";   // overrides
    public new string Kind() => "dog";          // hides (warning CS0108 without 'new')
}
Animal a = new Dog();
a.Speak();  // "Woof"
a.Kind();   // "animal"

C++ has an extra twist: name hiding of overloads. Declaring any f in a derived class hides all base overloads named f, even with different parameters:

struct Base    { void f(int); void f(double); };
struct Derived : Base { void f(const char*); };   // hides both Base::f overloads
Derived d;
d.f(1.0);      // error: no Derived::f(double) -- unless you add 'using Base::f;'

Access modifiers across languages

LevelJavaC#C++TypeScriptPythonKotlin
Same class onlyprivateprivate (default for members)private (default in class)private (compile-time) / #field (enforced at run time)__name (name-mangled to _Class__name)private
Subclassesprotected (also the whole package)protectedprotectedprotected_name (convention only)protected
Same package / assembly / module(no keyword) package-private, the defaultinternal (default for top-level types)— (friend grants named classes/functions access)— (module exports)—internal
Subclass or assembly—protected internal————
Subclass within assembly—private protected————
Everyonepublicpublicpublic (default in struct)public (default)everythingpublic (default)

Details interviewers like:

  • Java's protected is wider than package-private: same package plus subclasses elsewhere.
  • In Java and C++ access is per class, not per object: a method of Account can read other.balance of another Account. (Ruby's private is per-object.)
  • TypeScript private is erased — at run time (obj as any).secret works. ECMAScript #private fields are truly inaccessible.
  • C++ also has inheritance access: class D : private B makes B's public members private in D (an implemented-in-terms-of relationship, not is-a).
  • Python has no enforced privacy: "we are all consenting adults here". Name mangling exists to avoid accidental clashes in subclasses, not for security.
  • Java modules (JPMS) add a level above packages: exports controls which packages are visible outside the module at all.

Covariance and contravariance, briefly

If Cat is a subtype of Animal, what is the relationship between List<Cat> and List<Animal>, or between functions that take or return them?

VarianceMeaningSafe for
CovariantBox<Cat> is a subtype of Box<Animal>Producers / read-only (out)
ContravariantBox<Animal> is a subtype of Box<Cat>Consumers / write-only (in)
InvariantNo relationshipRead-write

Where it shows up in OOP:

  • Covariant return types in overriding (Java 5+, C++, C# 9+): Animal reproduce() may be overridden as Cat reproduce(). Safe because callers expecting an Animal get one.
  • Parameter types would have to be contravariant to be safe; Java, C# and C++ require them to be identical — a different parameter type is an overload, not an override (a classic equals(MyType) bug: it overloads equals(Object) instead of overriding it).
  • Java arrays are covariant and therefore unsafe: Object[] a = new String[1]; a[0] = 42; compiles and throws ArrayStoreException. Generics were made invariant to avoid this; use wildcards — PECS: Producer extends, Consumer super (Collections.copy(List<? super T> dst, List<? extends T> src)).
  • C# and Kotlin use declaration-site variance: IEnumerable<out T>, Comparer<in T>, Kotlin List<out E>.
  • TypeScript checks method parameters bivariantly (unsound but convenient); strictFunctionTypes makes function-typed properties contravariant but still exempts method syntax.

Object-Oriented Programming has more on generics and type erasure.

Multiple inheritance and the diamond problem

classDiagram
    class Device {
        +int id
        +powerOn()
    }
    class Scanner {
        +scan()
    }
    class Printer {
        +print()
    }
    class Copier {
        +copy()
    }
    Device <|-- Scanner
    Device <|-- Printer
    Scanner <|-- Copier
    Printer <|-- Copier

Two questions arise for Copier: does it contain one Device subobject or two (two id fields)? And if Scanner and Printer both override powerOn(), which one does Copier get?

C++ — by default, two copies: copier.id is ambiguous and you must write copier.Scanner::id. Virtual inheritance shares one base subobject:

struct Device  { int id = 0; virtual void powerOn() {} virtual ~Device() = default; };
struct Scanner : virtual Device { void powerOn() override {} };
struct Printer : virtual Device { void powerOn() override {} };
struct Copier  : Scanner, Printer {
    void powerOn() override { Scanner::powerOn(); Printer::powerOn(); }  // required: otherwise ambiguous final overrider
};

The cost: the most-derived class constructs the virtual base directly, and virtual base access goes through an offset stored in the vtable.

Java — no multiple inheritance of classes, hence no state diamond. Default methods can still collide; the compiler forces you to resolve it:

interface Scanner { default String status() { return "scanner ok"; } }
interface Printer { default String status() { return "printer ok"; } }
class Copier implements Scanner, Printer {
    @Override public String status() {             // mandatory -- compile error otherwise
        return Scanner.super.status() + ", " + Printer.super.status();
    }
}

Rules: a class method always wins over an interface default; a more specific interface wins over a less specific one; otherwise you must override.

Python — multiple inheritance with C3 linearisation producing a single Method Resolution Order:

class Device:
    def power_on(self): print("Device")
class Scanner(Device):
    def power_on(self): print("Scanner"); super().power_on()
class Printer(Device):
    def power_on(self): print("Printer"); super().power_on()
class Copier(Scanner, Printer): pass

print([c.__name__ for c in Copier.__mro__])   # ['Copier', 'Scanner', 'Printer', 'Device', 'object']
Copier().power_on()                            # Scanner, Printer, Device -- each exactly once

Note that Scanner's super() goes to Printer, not Device — cooperative multiple inheritance.

Mixins and traits — Scala traits and Ruby modules are linearised like Python. Rust traits and Go interfaces have no implementation inheritance between types at all; same-named methods from two traits are disambiguated at the call site (<T as Scanner>::status(&t)). PHP traits resolve conflicts with insteadof. The pattern is covered in OOP Fundamentals (mixins and traits section).

Composition vs inheritance, cohesion and coupling

Inheritance is the strongest coupling between two classes: the subclass depends on the parent's implementation details, not just its interface (the fragile base class problem). "Favour composition over inheritance" is covered with examples in Object-Oriented Programming and in the Strategy and Decorator patterns. The vocabulary for why is cohesion and coupling.

Cohesion — how strongly the responsibilities inside one module belong together. From worst to best:

CohesionElements grouped because…Example
CoincidentalNo reasonUtils with parseDate, sendEmail, md5
LogicalSame category of thingInputHandler handling mouse, keyboard and network input via a flag
TemporalRun at the same timeinit() that opens files, seeds caches and starts threads
ProceduralSteps of one procedurevalidateThenSaveThenEmail()
CommunicationalOperate on the same dataFunctions that all read the same customer record
SequentialOutput of one is input to the nextParse → transform → write
FunctionalAll contribute to one well-defined taskTaxCalculator

Coupling — how much one module depends on another. From worst to best:

CouplingDescription
ContentOne module reaches into another's internals (reflection on private fields)
CommonShared global mutable state
ExternalShared external format or device protocol
ControlPassing a flag that tells the other module what to do (render(true))
StampPassing a whole structure when only part is used
DataPassing only the primitive data needed
MessageCommunicating only through public method calls / messages

Aim for high cohesion, low coupling. SRP is a cohesion rule; DIP and ISP are coupling rules (SOLID).

The Liskov traps

The Liskov Substitution Principle says code written against a base type must keep working with any subtype: a subtype may weaken preconditions and strengthen postconditions, must preserve invariants, and must not throw new kinds of exceptions for operations the base promises. The theory is in Liskov Substitution; here are the traps that real code — including standard libraries — fell into.

TrapWhat goes wrongFix
Square extends RectanglesetWidth(5); setHeight(4); area() == 20 holds for every rectangle but fails for a square that keeps its sides equalMake shapes immutable, or have no inheritance between them — both implement Shape
Penguin extends Bird with fly() throwingEvery caller of bird.fly() must now handle an exception the contract never mentionedSplit capabilities: Bird, FlyingBird / Flyable
Read-only collection implementing a mutable interfaceCollections.unmodifiableList(...).add(x) throws UnsupportedOperationExceptionSeparate read and write interfaces (Kotlin List vs MutableList, C# IReadOnlyList)
java.util.Stack extends VectorA stack exposes add(index, e), remove(index) and get(i), breaking the LIFO invariantComposition: Deque<E> stack = new ArrayDeque<>()
java.util.Properties extends Hashtable<Object,Object>You can put non-String keys, after which getProperty silently ignores themComposition over inheritance
java.sql.Timestamp extends java.util.Datedate.equals(timestamp) can be true while timestamp.equals(date) is false — equals symmetry breaks, so it misbehaves in collectionsDo not add value components in a subclass of a concrete value class
Subclass strengthening a preconditionBase withdraw(amount) accepts any positive amount; SavingsAccount.withdraw rejects amounts over 500Model the limit in the base contract or use a policy object
equals with getClass() vs instanceofinstanceof plus added fields breaks symmetry; getClass() breaks substitutability (a subclass never equals its parent)Make value classes final (or records)

Other mechanics worth knowing

  • Object identity vs equality: == compares references in Java (and C# for classes by default); equals compares values. If you override equals you must override hashCode — equal objects must have equal hash codes or HashMap breaks.
  • Interfaces as types, not classes: declare variables by the interface (List<String> xs = new ArrayList<>()) so implementations can change without touching callers.
  • Sealed hierarchies: Java 17 sealed ... permits, Kotlin sealed, C# sealed classes, Scala sealed traits — a closed set of subtypes lets the compiler check exhaustive switches, giving you algebraic data types inside OOP.
  • Inner classes: a non-static inner class in Java holds a hidden reference to its outer instance — a common memory leak with listeners and Android activities. Use static nested classes when you do not need the outer object.
  • Object slicing (C++): assigning a Derived to a Base by value copies only the base part and loses the derived behaviour. Polymorphism in C++ needs pointers or references.

Part 2 — UML

UML (Unified Modeling Language, OMG standard, current version 2.5.1) has 14 diagram types. In practice — and in interviews — three matter: class diagrams for structure, sequence diagrams for interactions, and occasionally use-case diagrams for requirements. Everything below uses mermaid so you can render it in docs, PRs and on this site.

Class diagram notation

A class is a box with three compartments: name, attributes, operations.

classDiagram
    class Account {
        <<abstract>>
        -String id
        #Money balance
        ~AuditLog log
        +int count$
        +deposit(Money amount) void
        +withdraw(Money amount) boolean
        +interestRate()* double
        +nextId()$ String
    }
NotationMeaningMermaid
+public+name
-private-name
#protected#name
~package / internal~name
underlinestatic$ suffix
italicsabstract* suffix on a method, <<abstract>> on a class
<<interface>>stereotype<<interface>>
name : Typeattribute type (UML puts the type after)-String name or -name: String
op(p : T) : Roperation signature+op(T p) R

Relationships

RelationshipMeaningUML symbolMermaidCode smell test
AssociationA knows about / uses B as a structural linkSolid line, optional open arrow for navigabilityA --> B or A -- BA has a field of type B
AggregationWhole–part, parts can exist independently ("has-a", shared)Solid line, hollow diamond at the wholeWhole o-- PartA holds Bs that were created elsewhere and outlive A
CompositionWhole–part, part's lifetime bound to the whole (owned)Solid line, filled diamond at the wholeWhole *-- PartA creates its Bs and they die with it
GeneralisationInheritance (is-a)Solid line, hollow triangle at the parentParent <|-- Childextends
RealisationImplements an interfaceDashed line, hollow triangle at the interfaceInterface <|.. Implimplements
DependencyA uses B transiently (parameter, local, return type)Dashed line, open arrowA ..> BB appears only in a method signature or body
classDiagram
    class Car
    class Engine
    class Wheel
    class Driver
    class Garage
    class Vehicle
    class Insurable {
        <<interface>>
    }
    class FuelPump

    Vehicle <|-- Car : generalisation
    Insurable <|.. Car : realisation
    Car *-- "1" Engine : composition
    Car *-- "4" Wheel : composition
    Garage o-- "0..*" Car : aggregation
    Driver --> "0..1" Car : association
    Car ..> FuelPump : dependency

Reading it aloud: a Car is a Vehicle and is Insurable; it owns exactly one Engine and four Wheels (they are destroyed with the car); a Garage holds any number of Cars (the cars exist without the garage); a Driver drives zero or one Car; a Car uses a FuelPump only transiently while refuelling.

Aggregation vs composition — the test

Ask: if the whole is deleted, are the parts deleted too, and can a part belong to two wholes at once?

CompositionAggregation
LifetimePart dies with the wholePart survives the whole
SharingPart belongs to exactly one wholePart may be shared
CreationUsually created by the wholeUsually created elsewhere and passed in
ExamplesOrder *-- OrderLine, House *-- Room, Document *-- ParagraphTeam o-- Player, Department o-- Professor, Playlist o-- Song
class Order {                                   // composition
    private final List<OrderLine> lines = new ArrayList<>();
    void addLine(Product p, int qty) { lines.add(new OrderLine(p, qty)); }   // Order creates and owns lines
}

class Playlist {                                // aggregation
    private final List<Song> songs = new ArrayList<>();
    void add(Song s) { songs.add(s); }          // Song exists independently, may be in many playlists
}

Many teams skip aggregation entirely and draw plain association — UML 2 itself says aggregation semantics are "intentionally informal". Composition is the one worth getting right.

Multiplicity

NotationMeaning
1Exactly one
0..1Zero or one (optional)
* or 0..*Zero or more
1..*One or more
2..4Between two and four

Multiplicity is written at the far end of the relationship from the class it describes: Customer "1" --> "0..*" Order reads "one customer has zero or more orders; each order belongs to exactly one customer".

Worked model 1: Library management system

Requirements: members borrow book copies; a book (title, ISBN, authors) has many physical copies; a loan records member, copy, due date; overdue returns create fines; members can reserve a book when all copies are out; librarians add books and copies. Two member types — students (borrow 5, 14 days) and faculty (borrow 10, 30 days).

classDiagram
    class Library {
        -String name
        +addBook(Book b) void
        +addCopy(String isbn, String barcode) BookCopy
        +search(String query) List~Book~
    }
    class Book {
        -String isbn
        -String title
        -int year
        +availableCopies() List~BookCopy~
    }
    class Author {
        -String name
    }
    class BookCopy {
        -String barcode
        -CopyStatus status
        +isAvailable() boolean
    }
    class CopyStatus {
        <<enumeration>>
        AVAILABLE
        LOANED
        RESERVED
        LOST
    }
    class Member {
        <<abstract>>
        -String id
        -String name
        +maxLoans()* int
        +loanDays()* int
        +canBorrow() boolean
    }
    class Student {
        +maxLoans() int
        +loanDays() int
    }
    class Faculty {
        +maxLoans() int
        +loanDays() int
    }
    class Loan {
        -LocalDate issuedOn
        -LocalDate dueOn
        -LocalDate returnedOn
        +isOverdue(LocalDate today) boolean
        +close(LocalDate today) Fine
    }
    class Fine {
        -Money amount
        -boolean paid
        +pay() void
    }
    class Reservation {
        -LocalDateTime createdAt
        -ReservationStatus status
    }
    class FinePolicy {
        <<interface>>
        +compute(Loan loan, LocalDate today) Money
    }
    class PerDayFinePolicy {
        -Money perDay
        +compute(Loan loan, LocalDate today) Money
    }

    Library "1" *-- "0..*" Book : catalog
    Book "1" *-- "1..*" BookCopy : copies
    Book "0..*" o-- "1..*" Author : writtenBy
    BookCopy --> CopyStatus
    Member <|-- Student
    Member <|-- Faculty
    Member "1" --> "0..*" Loan : borrows
    Loan "0..*" --> "1" BookCopy : of
    Loan "1" --> "0..1" Fine : incurs
    Member "1" --> "0..*" Reservation : places
    Reservation "0..*" --> "1" Book : for
    Loan ..> FinePolicy : uses
    FinePolicy <|.. PerDayFinePolicy

Design decisions visible in the diagram:

  • Book vs BookCopy is the single most important modelling decision. Loans attach to copies (physical, have barcodes); reservations attach to books (any copy will do). Candidates who conflate them get stuck on "how many copies are available?".
  • Composition from Book to BookCopy: deleting a title from the catalogue deletes its copies. Aggregation from Book to Author: authors exist independently and write many books.
  • Member is abstract with maxLoans() and loanDays() abstract — the varying rules live in subclasses, the shared canBorrow() logic lives in the base (Template Method). If rules change often, replace the subclasses with a MembershipPolicy strategy instead.
  • FinePolicy is an interface realised by PerDayFinePolicy: the fine rule can change (capped, grace period) without touching Loan — Open/Closed in one arrow.
  • Loan depends on FinePolicy (dashed) because the policy is passed into close(), not stored.

The full code for this problem is in Design a Library Management System.

Worked model 2: Parking lot

Requirements: multiple floors; spots of types compact, regular, large and EV; vehicles of types motorcycle, car, van and truck; a ticket is issued at entry and paid at exit; pricing varies by hours and vehicle type; payment by card or cash.

classDiagram
    class ParkingLot {
        -String name
        +park(Vehicle v) Ticket
        +unpark(Ticket t, Payment p) Receipt
    }
    class Floor {
        -int number
        +findSpot(Vehicle v) ParkingSpot
    }
    class ParkingSpot {
        -String id
        -SpotType type
        -boolean occupied
        +canFit(Vehicle v) boolean
        +assign(Vehicle v) void
        +release() void
    }
    class SpotType {
        <<enumeration>>
        COMPACT
        REGULAR
        LARGE
        EV
    }
    class Vehicle {
        <<abstract>>
        -String plate
        +size()* VehicleSize
    }
    class Car
    class Motorcycle
    class Truck
    class Ticket {
        -String id
        -LocalDateTime entryTime
        -LocalDateTime exitTime
    }
    class SpotAllocationStrategy {
        <<interface>>
        +allocate(List~Floor~ floors, Vehicle v) ParkingSpot
    }
    class NearestFirstStrategy
    class PricingStrategy {
        <<interface>>
        +price(Ticket t) Money
    }
    class HourlyPricing
    class Payment {
        <<interface>>
        +pay(Money amount) boolean
    }
    class CardPayment
    class CashPayment
    class EntryGate
    class ExitGate

    ParkingLot "1" *-- "1..*" Floor
    Floor "1" *-- "1..*" ParkingSpot
    ParkingSpot --> SpotType
    ParkingSpot "0..1" --> "0..1" Vehicle : holds
    Vehicle <|-- Car
    Vehicle <|-- Motorcycle
    Vehicle <|-- Truck
    Ticket "1" --> "1" Vehicle
    Ticket "1" --> "1" ParkingSpot
    ParkingLot --> SpotAllocationStrategy
    SpotAllocationStrategy <|.. NearestFirstStrategy
    ParkingLot --> PricingStrategy
    PricingStrategy <|.. HourlyPricing
    Payment <|.. CardPayment
    Payment <|.. CashPayment
    ParkingLot ..> Payment : accepts
    ParkingLot "1" *-- "1..*" EntryGate
    ParkingLot "1" *-- "1..*" ExitGate

What an interviewer reads from this:

  • Composition chain ParkingLot *-- Floor *-- ParkingSpot — the physical structure.
  • Vehicle is associated, not composed: cars come and go and exist without the lot.
  • Two strategies (allocation and pricing) behind interfaces — the extension points the interviewer will push on ("add EV charging pricing", "allocate nearest to the elevator").
  • Payment is a dependency of unpark() because it is passed in per transaction.
  • The Ticket ties vehicle, spot and time together — it is what you look up at exit.

A full implementation, with concurrency notes on spot assignment, is in Design a Parking Lot.

Worked model 3: an interface-heavy notification module

A smaller example that exercises realisation, dependency and generalisation together — a typical "design a notification service" class diagram.

classDiagram
    class NotificationService {
        -Map~Channel, Notifier~ notifiers
        -TemplateEngine templates
        +send(User u, String templateId, Map~String, String~ vars) void
    }
    class Notifier {
        <<interface>>
        +send(Message m) DeliveryResult
    }
    class EmailNotifier
    class SmsNotifier
    class PushNotifier
    class RetryingNotifier {
        -Notifier inner
        -int maxAttempts
        +send(Message m) DeliveryResult
    }
    class Message {
        -String to
        -String subject
        -String body
    }
    class TemplateEngine {
        +render(String id, Map~String, String~ vars) Message
    }
    class User {
        -String email
        -String phone
        -Set~Channel~ preferences
    }

    Notifier <|.. EmailNotifier
    Notifier <|.. SmsNotifier
    Notifier <|.. PushNotifier
    Notifier <|.. RetryingNotifier
    RetryingNotifier o-- Notifier : wraps
    NotificationService o-- Notifier
    NotificationService --> TemplateEngine
    NotificationService ..> User
    TemplateEngine ..> Message : creates

RetryingNotifier both realises Notifier and wraps a Notifier — that two-arrow shape is the visual signature of the Decorator pattern (Structural Patterns). Learning to spot pattern shapes in diagrams is a real interview skill: Composite looks like a class that both realises and aggregates its own interface (with 0..*); Strategy is a context with an association to an interface with several realisations; Observer is a subject with 0..* association to an observer interface.

How to draw a class diagram in an LLD interview

flowchart TB
    A["1. Clarify requirements and scope (5 min)"] --> B["2. List nouns: candidate classes"]
    B --> C["3. List verbs: candidate methods and owners"]
    C --> D["4. Draw core entities and relationships with multiplicity"]
    D --> E["5. Mark variation points: interfaces and strategies"]
    E --> F["6. Add key attributes and method signatures only"]
    F --> G["7. Walk a use case through the diagram"]
    G --> H["8. Discuss extensions, concurrency, patterns"]
  1. Nouns become candidate classes, verbs become methods. Discard nouns that are just attributes (a "due date" is a field of Loan, not a class).
  2. Start with entities and relationships, not attributes. Boxes and lines first; the interviewer wants to see structure early.
  3. Get multiplicity right on the core relationships — that is where modelling mistakes show (one-to-many vs many-to-many changes the whole design).
  4. Put an interface wherever the requirements say "different kinds of", "may change", or "for example". Pricing, payment, notification channel, allocation rule.
  5. Prefer composition; use inheritance for genuine, stable is-a families (vehicle types, account types) and say why.
  6. Do not list every getter and setter. Show the attributes that drive behaviour and the public operations.
  7. Walk one use case through the diagram ("a car arrives: EntryGate calls ParkingLot.park, which asks the strategy for a spot…"). It catches missing associations instantly — this is when a sequence diagram helps.
  8. Name the patterns you used and the trade-offs (the LLD interview guide lists what interviewers score).

Reading someone else's diagram

Read it in this order: stereotypes and abstract classes (the extension points) → composition chains (the ownership tree, which tells you lifetimes and aggregate roots) → generalisation (the type families) → multiplicities (the cardinality rules that the database schema will need) → dependencies (what is passed in per call). Then sanity-check: any class with more than ~7 associations is probably a god class; any inheritance hierarchy deeper than three is suspicious; any bidirectional association needs a reason.

Mapping a class diagram to code

classDiagram
    class Customer {
        -String id
        +placeOrder(Cart c) Order
    }
    class Order {
        -OrderStatus status
        +total() Money
    }
    class OrderLine {
        -int qty
    }
    class Product
    Customer "1" --> "0..*" Order
    Order "1" *-- "1..*" OrderLine
    OrderLine "0..*" --> "1" Product
class Product { constructor(readonly sku: string, readonly price: number) {} }

class OrderLine {                          // part of the Order composition
  constructor(readonly product: Product, readonly qty: number) {}   // "0..*" --> "1" Product
  subtotal(): number { return this.product.price * this.qty; }
}

class Order {
  private readonly lines: OrderLine[] = [];              // *-- "1..*": owned, created here
  private status: "DRAFT" | "PLACED" = "DRAFT";
  constructor(readonly customerId: string) {}            // navigability Customer --> Order: Order stores only the id
  addLine(p: Product, qty: number): void { this.lines.push(new OrderLine(p, qty)); }
  total(): number { return this.lines.reduce((s, l) => s + l.subtotal(), 0); }
  place(): void {
    if (this.lines.length === 0) throw new Error("an order needs at least one line");   // enforces 1..*
    this.status = "PLACED";
  }
}

class Customer {
  private readonly orders: Order[] = [];                 // "1" --> "0..*"
  constructor(readonly id: string) {}
  placeOrder(items: Array<[Product, number]>): Order {
    const o = new Order(this.id);
    items.forEach(([p, q]) => o.addLine(p, q));
    o.place();
    this.orders.push(o);
    return o;
  }
}
Diagram elementCode
Association with multiplicity 0..*A collection field
Multiplicity 1A required constructor parameter, non-null field
Multiplicity 0..1An optional / nullable field
Lower bound 1..*An invariant checked in the constructor or a lifecycle method
CompositionThe whole creates the parts; parts are not exposed for external mutation
Navigability arrowWhich side holds the reference
DependencyA method parameter or local variable only

Sequence diagrams

A sequence diagram shows one scenario as messages between objects over time: lifelines run downward, arrows are calls, dashed arrows are returns, boxes are activations. Use one to validate a class diagram — every message must correspond to an operation on the receiving class, and every object that sends one must have a way to reach the receiver (an association or dependency).

Scenario: a student borrows a book.

sequenceDiagram
    actor S as Student
    participant L as Library
    participant M as Member
    participant B as Book
    participant C as BookCopy
    participant LN as Loan

    S->>L: borrow(memberId, isbn)
    L->>M: canBorrow()
    M-->>L: true
    L->>B: availableCopies()
    B-->>L: copies
    alt a copy is available
        L->>C: markLoaned()
        L->>LN: create(member, copy, dueOn)
        LN-->>L: loan
        L-->>S: loan confirmation
    else no copy available
        L->>B: addReservation(member)
        L-->>S: reserved, will notify
    end

Notation cheat sheet (mermaid in brackets):

ElementMeaning
Solid arrow (->>)Synchronous call
Dashed arrow (-->>)Return
Open arrow (-))Asynchronous message
alt / elseConditional branches
optOptional fragment (if without else)
loopRepetition
parParallel branches
Activation barThe participant is executing

Scenario: parking-lot exit with payment.

sequenceDiagram
    actor D as Driver
    participant G as ExitGate
    participant P as ParkingLot
    participant PR as PricingStrategy
    participant PAY as CardPayment
    participant SP as ParkingSpot

    D->>G: insert ticket
    G->>P: unpark(ticket)
    P->>PR: price(ticket)
    PR-->>P: amount
    P->>PAY: pay(amount)
    PAY-->>P: approved
    P->>SP: release()
    P-->>G: receipt
    G-->>D: open barrier

In an interview, one sequence diagram for the most complex flow is worth more than a third class diagram: it proves the design actually works.

Use-case diagrams

A use-case diagram shows actors (users or external systems) and the use cases (goals) they can achieve within a system boundary. It is a requirements tool — useful in the first five minutes of an LLD round to agree scope. Relationships: association (actor participates), include (a use case always contains another), extend (optionally adds behaviour), and generalisation between actors.

Mermaid has no native use-case diagram, so a flowchart with a subgraph as the system boundary is the usual substitute:

flowchart LR
    Student(["Student"])
    Faculty(["Faculty"])
    Librarian(["Librarian"])
    Clock(["Scheduler"])
    subgraph Library["Library System"]
        UC1(("Search catalogue"))
        UC2(("Borrow copy"))
        UC3(("Return copy"))
        UC4(("Reserve book"))
        UC5(("Pay fine"))
        UC6(("Add book or copy"))
        UC7(("Send overdue reminder"))
        UC8(("Authenticate"))
    end
    Student --- UC1
    Student --- UC2
    Student --- UC3
    Student --- UC4
    Student --- UC5
    Faculty --- UC2
    Librarian --- UC6
    Clock --- UC7
    UC2 -.->|"include"| UC8
    UC5 -.->|"extend from return"| UC3

Read: a student can search, borrow, return, reserve and pay fines; borrowing always includes authentication; paying a fine extends returning (it happens only when the return is late); a scheduler (an external actor, not a human) triggers overdue reminders.

Other UML diagrams in one line each

DiagramShowsWhen useful
Object diagramA snapshot of instances and linksExplaining a tricky multiplicity with concrete objects
State machineStates and transitions of one objectOrder lifecycle, vending machine, elevator — common in LLD
Activity diagramWorkflow with forks and joinsBusiness processes
Component diagramDeployable components and interfacesArchitecture docs
Deployment diagramNodes and what runs on themInfra docs (usually replaced by C4 or cloud diagrams)
Package diagramPackage dependenciesLayering rules

State machines are the most interview-relevant of these — see Design a Vending Machine and Design an Elevator System.


Part 3 — Tricky OOP Interview Questions

#QuestionCrisp answer
1Can you override a static method?No. Static methods are hidden; the call binds to the reference's declared type at compile time.
2Can you override a private method?No. Private methods are not inherited; a same-named method in the subclass is a new, unrelated method.
3Can you override a final method?No — that is what final means. A final class cannot be subclassed at all.
4Can a constructor be overridden?No. Constructors are not inherited; they can only be overloaded and chained.
5Can a constructor be private?Yes — singletons, static factories, utility classes, and builders use it.
6Can a constructor be virtual in C++?No: there is no vptr until the constructor runs. Use a virtual clone() (the "virtual constructor" idiom) instead.
7Why must a polymorphic base class have a virtual destructor?Deleting a derived object through a base pointer otherwise calls only the base destructor — undefined behaviour and leaks.
8Is overloading possible by return type alone?No in Java, C#, C++: the call f() would be ambiguous. (The JVM bytecode allows it; the language does not.)
9What decides which overload runs?The static types of the arguments, at compile time.
10What decides which override runs?The dynamic type of the receiver, at run time.
11Are fields polymorphic?No. Field access uses the declared type; a subclass field with the same name hides the parent's.
12What happens if a constructor calls an overridable method?Java and C#: the override runs before the subclass's fields are initialised (sees null/0). C++: the base version runs. Avoid it.
13Abstract class vs interface in one sentence?An abstract class is a partial implementation with state for an is-a family; an interface is a stateless capability contract a class may have many of.
14Can an abstract class have a constructor?Yes — it runs when a concrete subclass is constructed, to initialise shared state.
15Can an interface have a constructor or instance fields?No. Java interface fields are implicitly public static final.
16Why did Java 8 add default methods?To evolve interfaces (e.g. add stream() to Collection) without breaking every existing implementation.
17Two interfaces have the same default method. What happens?Compile error until the class overrides it; it can call either with A.super.m().
18How does C++ solve the diamond problem?virtual inheritance shares one base subobject; the most-derived class must resolve ambiguous overrides.
19How does Python resolve the diamond?C3 linearisation produces the MRO; super() follows it, so each class runs once.
20Composition vs aggregation?Composition: the part's lifetime is owned by the whole and it is not shared. Aggregation: the part exists independently and may be shared.
21Association vs dependency?Association is a structural link (a field). Dependency is transient use (a parameter or local).
22Shallow vs deep copy?Shallow copies the fields, so nested objects are shared; deep copies the whole reachable graph.
23Why is Java's clone() considered broken?Marker interface without the method, protected, shallow, bypasses constructors, cannot set final fields, checked exception. Use copy constructors.
24What is the rule of three/five/zero?If you define a destructor, copy constructor or copy assignment, define all three (five with moves). Better: own resources through RAII members and define none.
25What is object slicing?Copying a derived object into a base object by value in C++; the derived part and its overrides are lost.
26What is a vtable and a vptr?A per-class table of virtual function pointers, and a per-object hidden pointer to its class's table. A virtual call is two loads and an indirect call.
27What is the cost of a virtual call?A couple of loads and an indirect branch — but mostly the lost inlining. JITs and final devirtualise hot monomorphic sites.
28Is Java pass-by-reference?No. Java is always pass-by-value; for objects the value passed is a copy of the reference. Reassigning the parameter does not affect the caller; mutating the object does.
29If you override equals, what else must you override?hashCode, so equal objects hash equally; otherwise HashMap and HashSet break.
30What is the difference between == and equals()?== compares references (identity) for objects; equals compares logical value as the class defines it.
31Does protected in Java mean subclasses only?No — same package and subclasses.
32Can a subclass reduce the visibility of an overridden method?No; it may only keep or widen it. Narrowing would break substitutability.
33Can an overriding method throw a broader checked exception?No; it may throw the same, narrower, or none.
34What is a covariant return type?An override may return a subtype of the original return type.
35Why is List<Integer> not a List<Number>?Generics are invariant; otherwise you could add a Double to a list of Integers. Use List<? extends Number> to read.
36Square–Rectangle: why is it an LSP violation?Setting width then height on a Rectangle reference gives an unexpected area when the object is a square that couples its sides.
37Name a standard-library LSP violation.java.util.Stack extends Vector (exposes random access), Properties extends Hashtable, Timestamp extends Date (asymmetric equals).
38Static vs instance initialisation order in Java?Static blocks of base then derived (once, on first use); then per object: base field initialisers and constructor, then derived.
39Can you call a non-static method from a static method?Only through an explicit instance reference — there is no this.
40What is the difference between this and super?this is the current object (dynamic dispatch applies); super.m() calls the parent's implementation, bypassing dispatch for that call.
41What is the difference between early and late binding?Early: the call target is fixed at compile time (static, private, final, non-virtual). Late: chosen at run time from the object.
42Is multiple inheritance supported in Java?Of type and of behaviour (default methods): yes, through interfaces. Of state: no.
43What is a marker interface? Alternative?An empty interface used as a type tag (Serializable, Cloneable). Annotations are the modern alternative, though markers give compile-time type checking.
44Why make a class final / sealed?To protect invariants, prevent fragile-base-class issues, enable devirtualisation, and make value classes' equals safe.
45What is high cohesion and low coupling?Each module does one well-defined job; modules depend on each other only through narrow, stable interfaces.
46What is the fragile base class problem?Seemingly safe changes to a base class break subclasses that depended on its implementation details (e.g. addAll calling add).
47Why are finalizers bad?No guarantee they run or when, they run on an unknown thread, can resurrect objects, and slow GC. Use try-with-resources/using/with.
48What does a TypeScript interface compile to?Nothing — it is erased. Use an abstract class or a type guard if you need run-time checks.
49Can an object change its class at run time?Not in Java, C#, C++. It can in Python (obj.__class__ = Other) and Smalltalk — usually a sign you wanted the State pattern.
50Is-a vs has-a vs uses-a in UML?Generalisation (hollow triangle), composition/aggregation/association (diamond or plain line), dependency (dashed arrow).

Summary

ConceptKey point
OverloadingChosen at compile time from static argument types
OverridingChosen at run time from the receiver's dynamic type
VtablesOne table per class, one vptr per object; virtual call = two loads + indirect call
ConstructorsBase first; destruction in reverse; never call overridables from a constructor
CleanupDeterministic constructs (RAII, try-with-resources, using, with), never finalizers
CopyingShallow shares nested objects; prefer immutability or copy constructors over clone()
HidingStatic methods and fields are hidden, not overridden
AccessJava protected includes the package; TS private is erased; Python is convention
VarianceCovariant returns OK; Java arrays covariant and unsafe; generics invariant
DiamondC++ virtual inheritance, Java forced override, Python C3 MRO
UMLFilled diamond = composition, hollow diamond = aggregation, hollow triangle = inheritance, dashed triangle = realisation, dashed arrow = dependency

Practice Problems

1. Predict the output.

class A { void m(A a) { System.out.println("A.m(A)"); } }
class B extends A {
    void m(A a) { System.out.println("B.m(A)"); }
    void m(B b) { System.out.println("B.m(B)"); }
}
A x = new B();
B y = new B();
x.m(y);
y.m(x);
y.m(y);
Solution
B.m(A)
B.m(A)
B.m(B)

x.m(y): x's static type is A, which has only m(A), so the compiler binds m(A); at run time B overrides it → B.m(A). B.m(B) is an overload invisible through an A reference. y.m(x): static type B, argument static type A → only m(A) applies → B.m(A). y.m(y): both m(A) and m(B) apply; m(B) is more specific → B.m(B).

2. Predict the output.

class P { static String s() { return "P"; } String i() { return "P"; } String f = "P"; }
class C extends P { static String s() { return "C"; } String i() { return "C"; } String f = "C"; }
P p = new C();
System.out.println(p.s() + p.i() + p.f + ((C) p).f);
Solution

PCPC. Static method s() binds to declared type P; i() overrides → C; field f through a P reference → P; through the cast C reference → C.

3. Fix the bug.

class Logger { public: ~Logger() { flush(); } virtual void flush() {} };
class FileLogger : public Logger {
    FILE* f;
public:
    FileLogger(const char* p) : f(fopen(p, "w")) {}
    ~FileLogger() { fclose(f); }
    void flush() override { fflush(f); }
};
Logger* log = new FileLogger("app.log");
delete log;
Solution

Two bugs. (1) ~Logger is not virtual, so delete log calls only ~Logger — fclose never runs (and the behaviour is undefined). Make it virtual ~Logger(). (2) Even with that fixed, flush() called from ~Logger dispatches to Logger::flush, not FileLogger::flush, because by the time the base destructor runs the derived part is already destroyed and the vptr points at Logger's vtable — and f was already closed anyway. Flush in ~FileLogger before fclose, and do not call virtuals from destructors.

4. Shallow or deep? After the following, what does b.items contain?

const a = { name: "cart", items: [{ sku: "x", qty: 1 }] };
const b = { ...a };
const c = structuredClone(a);
a.items[0].qty = 5;
a.items.push({ sku: "y", qty: 1 });
Solution

b.items is the same array as a.items (spread is shallow): [{ sku: "x", qty: 5 }, { sku: "y", qty: 1 }]. c.items is an independent deep copy: [{ sku: "x", qty: 1 }].

5. Spot the LSP violation and redesign.

class Account {
    protected long balance;
    void withdraw(long amt) { if (amt <= 0) throw new IllegalArgumentException(); balance -= amt; }
}
class FixedDeposit extends Account {
    @Override void withdraw(long amt) { throw new UnsupportedOperationException("locked"); }
}
Solution

FixedDeposit refuses an operation the base type promises, so any code holding an Account that calls withdraw breaks when given a FixedDeposit. Redesign by capability: Account (balance, deposit), WithdrawableAccount extends Account (or a Withdrawable interface) implemented by SavingsAccount and CurrentAccount; FixedDeposit implements only Account plus a mature() operation. Code that withdraws asks for a Withdrawable, and the compiler stops you passing a fixed deposit.

6. Draw the class diagram. A university has departments; each department has professors and offers courses. A course can be offered by exactly one department; professors may belong to several departments; students enrol in courses, with a grade per enrolment; if the university is closed, departments cease to exist, but professors do not.

Solution
classDiagram
    class University
    class Department
    class Professor
    class Course
    class Student
    class Enrolment {
        -String grade
    }
    University "1" *-- "1..*" Department
    Department "1..*" o-- "0..*" Professor
    Department "1" *-- "0..*" Course : offers
    Professor "1" --> "0..*" Course : teaches
    Student "1" --> "0..*" Enrolment
    Enrolment "0..*" --> "1" Course

University–Department is composition (departments die with it). Department–Professor is aggregation, many-to-many (professors survive and are shared). Enrolment is an association class that carries the grade — the standard way to model attributes of a many-to-many link.

7. Diamond in Java. Does this compile? If not, fix it so Duck.describe() returns "swims, flies".

interface Swimmer { default String describe() { return "swims"; } }
interface Flyer   { default String describe() { return "flies"; } }
class Duck implements Swimmer, Flyer { }
Solution

It does not compile: Duck inherits unrelated defaults for describe(). Fix:

class Duck implements Swimmer, Flyer {
    @Override public String describe() { return Swimmer.super.describe() + ", " + Flyer.super.describe(); }
}

8. Sizes. On a 64-bit Itanium-ABI platform, what is sizeof of each?

struct E {};
struct V { virtual void f(); };
struct D : V { int x; };
struct M : V { virtual void g(); char c; };
Solution

E = 1 (non-zero size for distinct addresses). V = 8 (the vptr). D = 16 (vptr 8 + int 4 + 4 padding to 8-byte alignment). M = 16 (one vptr — new virtuals add vtable slots, not object size — plus char and padding).

9. Sequence diagram check. In the parking-lot exit sequence above, the interviewer adds "the gate must not open if payment fails". Which fragment do you add, and which class diagram element must exist for the message P->>PAY: pay(amount)?

Solution

Wrap the post-payment messages in an alt approved / else declined fragment: on decline, return an error to the gate and keep the barrier closed (the spot stays occupied). The message requires ParkingLot to be able to reach a Payment — in the class diagram that is the dependency ParkingLot ..> Payment (the payment object is passed into unpark) and Payment must declare pay(Money) boolean.

10. Cohesion and coupling. Classify: (a) ReportService.generate(boolean asPdf) that branches on the flag; (b) a Helpers class with slugify, retryHttp and formatCurrency; (c) InvoiceCalculator whose methods all compute parts of an invoice total.

Solution

(a) Control coupling — the caller dictates the callee's internal logic via a flag; split into generatePdf() and generateHtml() or inject a renderer. (b) Coincidental cohesion — split by responsibility. (c) Functional cohesion — the goal.


Interview Questions

"Explain runtime polymorphism and how it is implemented." A call through a base-type reference runs the override belonging to the object's actual class. In C++, Java and C#, each polymorphic class has a vtable of function pointers and each object carries a hidden vptr to its class's vtable; the compiler knows the slot index for the method, so a call loads the vptr, loads the slot and calls indirectly. JITs remove much of the cost by inlining at call sites that only ever see one type.

"What is the difference between method overloading and overriding — and what happens when you mix them?" Overloading is several methods with the same name but different parameters, selected at compile time by the static argument types. Overriding replaces an inherited method with the same signature, selected at run time by the receiver's type. When mixed, the compiler first fixes the overload signature using static types, then dispatch picks the override of that signature — the runtime type of the arguments is never consulted, which is why double dispatch needs the Visitor pattern.

"When would you choose an abstract class over an interface?" When subclasses share state and implementation, need constructors or protected helpers, and form a genuine stable is-a family — especially for a Template Method skeleton. Choose an interface for capabilities that unrelated classes share, when you need multiple supertypes, or for seams used by dependency injection and testing. Often you provide both: an interface plus an abstract skeletal implementation.

"Why is composition generally preferred over inheritance?" Inheritance couples a subclass to its parent's implementation, is fixed at compile time and exposes the whole parent API whether it makes sense or not (Stack extends Vector). Composition depends only on an interface, can be changed at run time, and lets you combine behaviours without an explosion of subclasses. Use inheritance for true substitutable is-a relationships.

"What's the difference between aggregation and composition? Give a code-level difference." Composition means the whole owns the part's lifetime and the part is not shared — the whole typically creates it (Order creates its OrderLines) and it is never handed out for others to keep. Aggregation means the part is created elsewhere, passed in, may be shared and outlives the whole (Playlist and Song).

"How do you approach drawing a class diagram for an LLD problem?" Clarify requirements, extract nouns into classes and verbs into methods, draw the core entities and their relationships with multiplicities first, put interfaces at every point of variation, add only the attributes and operations that matter, then walk a key use case through it (ideally as a sequence diagram) to check that every interaction has a path, and finally discuss extensions and patterns.

"What is the diamond problem and how do different languages handle it?" A class inheriting from two classes that share a base gets an ambiguous method and possibly two copies of the base's state. C++ offers virtual inheritance for a single shared base and requires an explicit final override; Java forbids multiple class inheritance and makes you override conflicting default methods; Python linearises with C3 so super() visits each class once; Rust and Go avoid implementation inheritance altogether.

"What is the Liskov Substitution Principle, with a real example of a violation?" Subtypes must be usable anywhere their base type is expected without surprising the caller: no stronger preconditions, no weaker postconditions, preserved invariants. java.util.Stack extends Vector, so a "stack" lets you insert at any index — the LIFO invariant cannot be protected. Collections.unmodifiableList throwing on add is another: the List contract allows add, so callers get exceptions they were never warned about.

"Why should you never call an overridable method from a constructor?" In Java and C#, the override runs before the subclass's fields have been initialised, so it sees default values (null, 0). In C++, the call does not dispatch to the subclass at all. Either way the behaviour differs from what the author intended. Make such methods private or final, or move the work to a factory method that runs after construction.

"Shallow copy vs deep copy — and how do you copy safely in Java?" A shallow copy duplicates the top-level fields so nested mutable objects are shared; a deep copy duplicates the whole reachable graph. In Java, avoid clone() and write a copy constructor or static factory that deep-copies mutable fields — or design the type to be immutable so sharing is safe.