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:
| Kind | Also called | Resolved | Example |
|---|---|---|---|
| Ad-hoc | Overloading | Compile time | print(int), print(String) |
| Subtype (inclusion) | Overriding, runtime polymorphism | Run time | Shape s = new Circle(); s.area() |
| Parametric | Generics, templates | Compile time (C++ templates, Rust) or erased (Java) | List<T>, std::vector<T> |
| Coercion | Implicit conversion | Compile time | double 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
| Overloading | Overriding | |
|---|---|---|
| What | Same name, different parameter lists, usually in the same class | Subclass redefines an inherited method with the same signature |
| Decided by | The static (declared) types of the arguments | The dynamic (runtime) type of the receiver object |
| When | Compile time | Run time |
| Return type | May differ (but cannot be the only difference) | Same, or covariant (a subtype) |
| Access | Any | Cannot be more restrictive than the overridden method |
| Exceptions (Java) | Any | Cannot throw broader checked exceptions |
| Applies to static methods? | Yes | No — 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):
- Compile time — pick the overload. The compiler sees
p : Printerandx : Object. OfPrinter's methods, onlyprint(Object)applies to anObjectargument. The call is bound to the signatureprint(Object). - Run time — pick the override. The receiver is actually a
FancyPrinter, so itsprint(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:
- Exact match or widening primitive conversion, no boxing, no varargs (
int→longis allowed). - Allow boxing and unboxing (
int→Integer). - 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::bardirectly, 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.
| Language | Default for instance methods | Opt-in / opt-out |
|---|---|---|
| C++ | Static | virtual makes a method dynamically dispatched |
| C# | Static | virtual / abstract / override; sealed stops further overriding |
| Java | Dynamic | final, private and static methods are statically bound |
| Kotlin | Dynamic but final by default | open to allow overriding |
| Python, Ruby, JavaScript | Dynamic (attribute lookup at call time) | — |
| Swift | Dynamic for classes | final, struct methods are static |
| Go | Static for concrete types | Interface values dispatch dynamically through an itab |
| Rust | Static (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"; }
};
- 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.
- Every object of a polymorphic class gets a hidden pointer, the vptr, usually at offset 0, pointing at its class's vtable.
- 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:
| Fact | Why |
|---|---|
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 object | Vtables are shared, read-only data |
| A virtual call costs ~2 loads + an indirect branch | Usually cheap when the branch predictor guesses right; the real cost is that it blocks inlining |
final / sealed / devirtualisation | If 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 virtual | There is no object, and so no vptr, until the constructor runs |
| Destructors should be virtual in a polymorphic base | delete basePtr on a non-virtual destructor calls only ~Base — undefined behaviour, leaks |
| Virtual call in a C++ constructor calls the base version | During Shape's constructor the vptr points at Shape's vtable; it is updated as each derived constructor starts |
| Multiple inheritance needs multiple vptrs | Each 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 Traitis 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.
| Feature | Java abstract class | Java interface (8+) | C# interface (8+) | TypeScript interface | C++ |
|---|---|---|---|---|---|
| Instance fields | Yes | No (only public static final constants) | No (static fields allowed in C# 8+) | Property declarations only | Abstract base class can have anything |
| Constructors | Yes | No | No | No | Yes |
| Method bodies | Yes | default, static, and private (9+) methods | Default implementations, static, private | No — declarations only | Pure virtual = 0 (may still have a body) |
| Multiple inheritance | One superclass | A class implements many | Many | implements many; interfaces can extends many | Multiple inheritance of classes |
| Member access | Any | Methods implicitly public | Any access since C# 8 | Public | Any |
| Exists at run time | Yes | Yes | Yes | No — erased (structural, compile-time only) | Yes |
| State in hierarchy | Shared, protected state | None | None | None | Yes |
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
implementsrequired, and they vanish from the compiled JavaScript. You cannot dox instanceof MyInterface. Abstract classes, by contrast, compile to real JavaScript classes and supportinstanceof. - C++ has no
interfacekeyword. 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 when | Choose an interface when |
|---|---|
| Subclasses share real state and code | Unrelated classes need a common capability |
| You need constructors or protected members | You need multiple "inheritance" of type |
| The hierarchy is a genuine is-a family | You want to swap implementations (DI, mocking) |
| You want to provide a Template Method skeleton | You 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:
- Memory is allocated (zeroed in Java).
A's constructor runs completely (includingA's field initialisers), thenB's, thenC's — base first.- 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 touchthismay now come beforesuper(...)— useful for validating arguments before delegating. - C++ uses the member initialiser list:
Circle(double r) : Shape("circle"), r_(r) {}; C++11 added delegating constructorsCircle() : 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
| Language | Deterministic cleanup | Non-deterministic hook | Notes |
|---|---|---|---|
| C++ | Destructor, runs at scope exit or delete | — | RAII: resources owned by objects, released in destructors. std::unique_ptr, std::lock_guard |
| Rust | Drop::drop at scope end | — | Ownership makes RAII the only model |
| Java | try-with-resources + AutoCloseable | finalize() — deprecated (Java 9), deprecated for removal (Java 18, JEP 421); use java.lang.ref.Cleaner as a safety net | Finalizers 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 |
| Python | with + context managers | __del__ | CPython refcounting usually runs __del__ promptly, but reference cycles and other interpreters make it unreliable |
| JavaScript | using declarations with Symbol.dispose (explicit resource management, shipping in modern engines and TypeScript 5.2+) | FinalizationRegistry | Finalisation callbacks are best-effort only |
| Go | defer 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::stringand 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++
staticdata members need one out-of-class definition (orinline staticsince C++17). - Python distinguishes
@staticmethod(no implicit argument) from@classmethod(receives the classcls, 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
| Level | Java | C# | C++ | TypeScript | Python | Kotlin |
|---|---|---|---|---|---|---|
| Same class only | private | private (default for members) | private (default in class) | private (compile-time) / #field (enforced at run time) | __name (name-mangled to _Class__name) | private |
| Subclasses | protected (also the whole package) | protected | protected | protected | _name (convention only) | protected |
| Same package / assembly / module | (no keyword) package-private, the default | internal (default for top-level types) | — (friend grants named classes/functions access) | — (module exports) | — | internal |
| Subclass or assembly | — | protected internal | — | — | — | — |
| Subclass within assembly | — | private protected | — | — | — | — |
| Everyone | public | public | public (default in struct) | public (default) | everything | public (default) |
Details interviewers like:
- Java's
protectedis wider than package-private: same package plus subclasses elsewhere. - In Java and C++ access is per class, not per object: a method of
Accountcan readother.balanceof anotherAccount. (Ruby'sprivateis per-object.) - TypeScript
privateis erased — at run time(obj as any).secretworks. ECMAScript#privatefields are truly inaccessible. - C++ also has inheritance access:
class D : private Bmakes 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:
exportscontrols 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?
| Variance | Meaning | Safe for |
|---|---|---|
| Covariant | Box<Cat> is a subtype of Box<Animal> | Producers / read-only (out) |
| Contravariant | Box<Animal> is a subtype of Box<Cat> | Consumers / write-only (in) |
| Invariant | No relationship | Read-write |
Where it shows up in OOP:
- Covariant return types in overriding (Java 5+, C++, C# 9+):
Animal reproduce()may be overridden asCat reproduce(). Safe because callers expecting anAnimalget 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 overloadsequals(Object)instead of overriding it). - Java arrays are covariant and therefore unsafe:
Object[] a = new String[1]; a[0] = 42;compiles and throwsArrayStoreException. Generics were made invariant to avoid this; use wildcards — PECS: Producerextends, Consumersuper(Collections.copy(List<? super T> dst, List<? extends T> src)). - C# and Kotlin use declaration-site variance:
IEnumerable<out T>,Comparer<in T>, KotlinList<out E>. - TypeScript checks method parameters bivariantly (unsound but convenient);
strictFunctionTypesmakes 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:
| Cohesion | Elements grouped because… | Example |
|---|---|---|
| Coincidental | No reason | Utils with parseDate, sendEmail, md5 |
| Logical | Same category of thing | InputHandler handling mouse, keyboard and network input via a flag |
| Temporal | Run at the same time | init() that opens files, seeds caches and starts threads |
| Procedural | Steps of one procedure | validateThenSaveThenEmail() |
| Communicational | Operate on the same data | Functions that all read the same customer record |
| Sequential | Output of one is input to the next | Parse → transform → write |
| Functional | All contribute to one well-defined task | TaxCalculator |
Coupling — how much one module depends on another. From worst to best:
| Coupling | Description |
|---|---|
| Content | One module reaches into another's internals (reflection on private fields) |
| Common | Shared global mutable state |
| External | Shared external format or device protocol |
| Control | Passing a flag that tells the other module what to do (render(true)) |
| Stamp | Passing a whole structure when only part is used |
| Data | Passing only the primitive data needed |
| Message | Communicating 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.
| Trap | What goes wrong | Fix |
|---|---|---|
| Square extends Rectangle | setWidth(5); setHeight(4); area() == 20 holds for every rectangle but fails for a square that keeps its sides equal | Make shapes immutable, or have no inheritance between them — both implement Shape |
Penguin extends Bird with fly() throwing | Every caller of bird.fly() must now handle an exception the contract never mentioned | Split capabilities: Bird, FlyingBird / Flyable |
| Read-only collection implementing a mutable interface | Collections.unmodifiableList(...).add(x) throws UnsupportedOperationException | Separate read and write interfaces (Kotlin List vs MutableList, C# IReadOnlyList) |
java.util.Stack extends Vector | A stack exposes add(index, e), remove(index) and get(i), breaking the LIFO invariant | Composition: Deque<E> stack = new ArrayDeque<>() |
java.util.Properties extends Hashtable<Object,Object> | You can put non-String keys, after which getProperty silently ignores them | Composition over inheritance |
java.sql.Timestamp extends java.util.Date | date.equals(timestamp) can be true while timestamp.equals(date) is false — equals symmetry breaks, so it misbehaves in collections | Do not add value components in a subclass of a concrete value class |
| Subclass strengthening a precondition | Base withdraw(amount) accepts any positive amount; SavingsAccount.withdraw rejects amounts over 500 | Model the limit in the base contract or use a policy object |
equals with getClass() vs instanceof | instanceof 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);equalscompares values. If you overrideequalsyou must overridehashCode— equal objects must have equal hash codes orHashMapbreaks. - 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, Kotlinsealed, C#sealedclasses, Scalasealedtraits — a closed set of subtypes lets the compiler check exhaustiveswitches, 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
staticnested classes when you do not need the outer object. - Object slicing (C++): assigning a
Derivedto aBaseby 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
}
| Notation | Meaning | Mermaid |
|---|---|---|
+ | public | +name |
- | private | -name |
# | protected | #name |
~ | package / internal | ~name |
| underline | static | $ suffix |
| italics | abstract | * suffix on a method, <<abstract>> on a class |
<<interface>> | stereotype | <<interface>> |
name : Type | attribute type (UML puts the type after) | -String name or -name: String |
op(p : T) : R | operation signature | +op(T p) R |
Relationships
| Relationship | Meaning | UML symbol | Mermaid | Code smell test |
|---|---|---|---|---|
| Association | A knows about / uses B as a structural link | Solid line, optional open arrow for navigability | A --> B or A -- B | A has a field of type B |
| Aggregation | Whole–part, parts can exist independently ("has-a", shared) | Solid line, hollow diamond at the whole | Whole o-- Part | A holds Bs that were created elsewhere and outlive A |
| Composition | Whole–part, part's lifetime bound to the whole (owned) | Solid line, filled diamond at the whole | Whole *-- Part | A creates its Bs and they die with it |
| Generalisation | Inheritance (is-a) | Solid line, hollow triangle at the parent | Parent <|-- Child | extends |
| Realisation | Implements an interface | Dashed line, hollow triangle at the interface | Interface <|.. Impl | implements |
| Dependency | A uses B transiently (parameter, local, return type) | Dashed line, open arrow | A ..> B | B 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?
| Composition | Aggregation | |
|---|---|---|
| Lifetime | Part dies with the whole | Part survives the whole |
| Sharing | Part belongs to exactly one whole | Part may be shared |
| Creation | Usually created by the whole | Usually created elsewhere and passed in |
| Examples | Order *-- OrderLine, House *-- Room, Document *-- Paragraph | Team 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
| Notation | Meaning |
|---|---|
1 | Exactly one |
0..1 | Zero or one (optional) |
* or 0..* | Zero or more |
1..* | One or more |
2..4 | Between 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:
BookvsBookCopyis 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
BooktoBookCopy: deleting a title from the catalogue deletes its copies. Aggregation fromBooktoAuthor: authors exist independently and write many books. Memberis abstract withmaxLoans()andloanDays()abstract — the varying rules live in subclasses, the sharedcanBorrow()logic lives in the base (Template Method). If rules change often, replace the subclasses with aMembershipPolicystrategy instead.FinePolicyis an interface realised byPerDayFinePolicy: the fine rule can change (capped, grace period) without touchingLoan— Open/Closed in one arrow.Loandepends onFinePolicy(dashed) because the policy is passed intoclose(), 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. Vehicleis 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").
Paymentis a dependency ofunpark()because it is passed in per transaction.- The
Ticketties 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"]
- Nouns become candidate classes, verbs become methods. Discard nouns that are just attributes (a "due date" is a field of
Loan, not a class). - Start with entities and relationships, not attributes. Boxes and lines first; the interviewer wants to see structure early.
- Get multiplicity right on the core relationships — that is where modelling mistakes show (one-to-many vs many-to-many changes the whole design).
- Put an interface wherever the requirements say "different kinds of", "may change", or "for example". Pricing, payment, notification channel, allocation rule.
- Prefer composition; use inheritance for genuine, stable is-a families (vehicle types, account types) and say why.
- Do not list every getter and setter. Show the attributes that drive behaviour and the public operations.
- Walk one use case through the diagram ("a car arrives:
EntryGatecallsParkingLot.park, which asks the strategy for a spot…"). It catches missing associations instantly — this is when a sequence diagram helps. - 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 element | Code |
|---|---|
Association with multiplicity 0..* | A collection field |
Multiplicity 1 | A required constructor parameter, non-null field |
Multiplicity 0..1 | An optional / nullable field |
Lower bound 1..* | An invariant checked in the constructor or a lifecycle method |
| Composition | The whole creates the parts; parts are not exposed for external mutation |
| Navigability arrow | Which side holds the reference |
| Dependency | A 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):
| Element | Meaning |
|---|---|
Solid arrow (->>) | Synchronous call |
Dashed arrow (-->>) | Return |
Open arrow (-)) | Asynchronous message |
alt / else | Conditional branches |
opt | Optional fragment (if without else) |
loop | Repetition |
par | Parallel branches |
| Activation bar | The 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
| Diagram | Shows | When useful |
|---|---|---|
| Object diagram | A snapshot of instances and links | Explaining a tricky multiplicity with concrete objects |
| State machine | States and transitions of one object | Order lifecycle, vending machine, elevator — common in LLD |
| Activity diagram | Workflow with forks and joins | Business processes |
| Component diagram | Deployable components and interfaces | Architecture docs |
| Deployment diagram | Nodes and what runs on them | Infra docs (usually replaced by C4 or cloud diagrams) |
| Package diagram | Package dependencies | Layering 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
| # | Question | Crisp answer |
|---|---|---|
| 1 | Can you override a static method? | No. Static methods are hidden; the call binds to the reference's declared type at compile time. |
| 2 | Can you override a private method? | No. Private methods are not inherited; a same-named method in the subclass is a new, unrelated method. |
| 3 | Can you override a final method? | No — that is what final means. A final class cannot be subclassed at all. |
| 4 | Can a constructor be overridden? | No. Constructors are not inherited; they can only be overloaded and chained. |
| 5 | Can a constructor be private? | Yes — singletons, static factories, utility classes, and builders use it. |
| 6 | Can a constructor be virtual in C++? | No: there is no vptr until the constructor runs. Use a virtual clone() (the "virtual constructor" idiom) instead. |
| 7 | Why 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. |
| 8 | Is 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.) |
| 9 | What decides which overload runs? | The static types of the arguments, at compile time. |
| 10 | What decides which override runs? | The dynamic type of the receiver, at run time. |
| 11 | Are fields polymorphic? | No. Field access uses the declared type; a subclass field with the same name hides the parent's. |
| 12 | What 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. |
| 13 | Abstract 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. |
| 14 | Can an abstract class have a constructor? | Yes — it runs when a concrete subclass is constructed, to initialise shared state. |
| 15 | Can an interface have a constructor or instance fields? | No. Java interface fields are implicitly public static final. |
| 16 | Why did Java 8 add default methods? | To evolve interfaces (e.g. add stream() to Collection) without breaking every existing implementation. |
| 17 | Two interfaces have the same default method. What happens? | Compile error until the class overrides it; it can call either with A.super.m(). |
| 18 | How does C++ solve the diamond problem? | virtual inheritance shares one base subobject; the most-derived class must resolve ambiguous overrides. |
| 19 | How does Python resolve the diamond? | C3 linearisation produces the MRO; super() follows it, so each class runs once. |
| 20 | Composition 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. |
| 21 | Association vs dependency? | Association is a structural link (a field). Dependency is transient use (a parameter or local). |
| 22 | Shallow vs deep copy? | Shallow copies the fields, so nested objects are shared; deep copies the whole reachable graph. |
| 23 | Why is Java's clone() considered broken? | Marker interface without the method, protected, shallow, bypasses constructors, cannot set final fields, checked exception. Use copy constructors. |
| 24 | What 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. |
| 25 | What is object slicing? | Copying a derived object into a base object by value in C++; the derived part and its overrides are lost. |
| 26 | What 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. |
| 27 | What 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. |
| 28 | Is 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. |
| 29 | If you override equals, what else must you override? | hashCode, so equal objects hash equally; otherwise HashMap and HashSet break. |
| 30 | What is the difference between == and equals()? | == compares references (identity) for objects; equals compares logical value as the class defines it. |
| 31 | Does protected in Java mean subclasses only? | No — same package and subclasses. |
| 32 | Can a subclass reduce the visibility of an overridden method? | No; it may only keep or widen it. Narrowing would break substitutability. |
| 33 | Can an overriding method throw a broader checked exception? | No; it may throw the same, narrower, or none. |
| 34 | What is a covariant return type? | An override may return a subtype of the original return type. |
| 35 | Why 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. |
| 36 | Square–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. |
| 37 | Name a standard-library LSP violation. | java.util.Stack extends Vector (exposes random access), Properties extends Hashtable, Timestamp extends Date (asymmetric equals). |
| 38 | Static 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. |
| 39 | Can you call a non-static method from a static method? | Only through an explicit instance reference — there is no this. |
| 40 | What 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. |
| 41 | What 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. |
| 42 | Is multiple inheritance supported in Java? | Of type and of behaviour (default methods): yes, through interfaces. Of state: no. |
| 43 | What 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. |
| 44 | Why make a class final / sealed? | To protect invariants, prevent fragile-base-class issues, enable devirtualisation, and make value classes' equals safe. |
| 45 | What is high cohesion and low coupling? | Each module does one well-defined job; modules depend on each other only through narrow, stable interfaces. |
| 46 | What 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). |
| 47 | Why 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. |
| 48 | What does a TypeScript interface compile to? | Nothing — it is erased. Use an abstract class or a type guard if you need run-time checks. |
| 49 | Can 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. |
| 50 | Is-a vs has-a vs uses-a in UML? | Generalisation (hollow triangle), composition/aggregation/association (diamond or plain line), dependency (dashed arrow). |
Summary
| Concept | Key point |
|---|---|
| Overloading | Chosen at compile time from static argument types |
| Overriding | Chosen at run time from the receiver's dynamic type |
| Vtables | One table per class, one vptr per object; virtual call = two loads + indirect call |
| Constructors | Base first; destruction in reverse; never call overridables from a constructor |
| Cleanup | Deterministic constructs (RAII, try-with-resources, using, with), never finalizers |
| Copying | Shallow shares nested objects; prefer immutability or copy constructors over clone() |
| Hiding | Static methods and fields are hidden, not overridden |
| Access | Java protected includes the package; TS private is erased; Python is convention |
| Variance | Covariant returns OK; Java arrays covariant and unsafe; generics invariant |
| Diamond | C++ virtual inheritance, Java forced override, Python C3 MRO |
| UML | Filled 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.
Related Pages
- Object-Oriented Programming — the four pillars, SOLID, patterns overview, OOP in five languages
- SOLID Principles — and Liskov Substitution in depth
- Design Patterns — Creational, Structural, Behavioral
- LLD Interviews — Parking Lot, Library Management, Vending Machine, Elevator System
- Functional Programming — the other paradigm, and where it complements OOP
- How Computers Work — the memory and cache behaviour behind object layout and indirect calls