PrepStack › CS Fundamentals › OOP & SOLID
OOP & SOLID interview cheat sheet
Four pillars, class design, SOLID, design patterns and LLD
OOP rounds check whether you can model a problem with objects and explain why one design is better than another. Expect definitions (pillars, overloading vs overriding, abstract class vs interface), then SOLID with a violation and its fix, then 'which pattern would you use here?', and finally a small low-level design like a parking lot. Code is in Java 21 unless marked. Read the 15-minute revision, then switch to Quiz mode and answer out loud.
15-minute revision
- A class is a blueprint (fields + methods). An object is one instance of it in memory, with its own state and identity.
- Four pillars: encapsulation (hide state, expose behaviour), abstraction (show what, hide how), inheritance (reuse via is-a), polymorphism (one interface, many forms).
- Overloading = same name, different parameter list, chosen at compile time. Overriding = same signature in a subclass, chosen at run time from the actual object.
- Overriding rules: same signature, covariant return allowed, access cannot be narrowed, no new or broader checked exceptions.
static,privateandfinalmethods are not overridden. - Abstract class: shared state, constructors, single inheritance. Interface: a capability/contract, multiple implementation,
default/static/privatemethods but no instance state. - Java access:
private(class) < package-private (package) <protected(package + subclasses) <public(everyone). staticbelongs to the class (one copy). Instance members belong to each object. Static methods have nothisand are hidden, not overridden.- Association = uses; aggregation = has-a, parts live on their own (◇); composition = owns, parts die with the whole (◆).
- Favour composition over inheritance: inheritance breaks encapsulation and ties you to the parent's internals. Use it only for a true, stable is-a.
- Diamond problem: Java bans multiple class inheritance; clashing interface defaults must be overridden (
A.super.m()). Python uses the C3 MRO; C++ usesvirtualinheritance. - Aim for low coupling, high cohesion. Law of Demeter: talk only to your direct friends; avoid
a.getB().getC().do(). - SOLID: Single responsibility, Open/closed, Liskov substitution, Interface segregation, Dependency inversion.
- LSP classic: a mutable
Square extends Rectanglebreaks callers that set width and height separately. Fix with immutable shapes or no is-a link. - Patterns: creational (Singleton, Factory Method, Abstract Factory, Builder, Prototype), structural (Adapter, Decorator, Facade, Proxy, Composite), behavioural (Strategy, Observer, Command, Template Method, State, Chain of Responsibility, Iterator).
- Best Java singleton: enum or the holder idiom. Double-checked locking needs a
volatilefield. - Override
equals⇒ overridehashCode. Never mutate a field used inhashCodewhile the object sits in a hash set or map key.
OOP Foundations
Class vs object
A class is the blueprint; an object is a live instance with its own state, behaviour and identity.
- A class declares fields (state) and methods (behaviour). It takes no heap memory for instance data until you create objects.
- An object is created with
new. It lives on the heap and has state (field values), behaviour (methods) and identity (its own address). - A variable such as
Car cholds a reference to an object, not the object itself. Two references can point to the same object. ==on references compares identity.equals()compares logical equality, if the class overrides it.staticfields belong to the class and are shared. Instance fields are copied into every object.- OOP models a system as objects that send messages (call methods) to each other, instead of functions working on shared global data.
Interview questions
- What is the difference between a class and an object?
- What is OOP and why use it?
- What are the state, behaviour and identity of an object?
Encapsulation & abstraction
Encapsulation hides an object's data behind methods that guard its rules; abstraction hides how something works behind a simple contract.
- Encapsulation: make fields
privateand change them only through methods that check the rules (invariants). The object stays valid no matter who calls it. - Do not leak mutable internals. Return copies or unmodifiable views (
List.copyOf) instead of the real list. - Getters and setters for every field is not real encapsulation. Prefer behaviour methods like
withdraw()oversetBalance(). - Abstraction: expose only what a caller needs (
pay(amount)) and hide the how (tokenising, retries, HTTP). Achieved with interfaces and abstract classes. - Encapsulation is about protecting data (implementation level). Abstraction is about simplifying the view (design level). They work together.
- Benefits: callers cannot break invariants, you can change internals freely, and code is easier to test.
Interview questions
- What is encapsulation?
- Difference between encapsulation and abstraction?
- Are getters and setters good encapsulation?
Inheritance, constructors, this & super
A subclass reuses and extends a parent (is-a); constructors run parent-first, and this/super pick the current or parent version.
- Inheritance (
extends) gives a subclass the parent's non-private members. Java allows one parent class but many interfaces. - Types: single, multilevel (A→B→C), hierarchical (one parent, many children). Multiple and hybrid inheritance of classes are not allowed in Java.
- A constructor has the class name and no return type. If you write none, Java adds a no-arg default constructor. Constructors are not inherited.
this(...)calls another constructor in the same class;super(...)calls the parent constructor. Either must be the first statement. If you write neither, Java insertssuper().this.xmeans the current object's field.super.method()calls the parent's version of an overridden method.- Order of creation: static blocks (parent then child, once per class load) → parent instance initialisers and constructor → child instance initialisers and constructor.
final classcannot be extended;finalmethod cannot be overridden. Aprivateconstructor stops outside creation (utility classes, singletons).
Interview questions
- What is inheritance and what types does Java support?
- Difference between
thisandsuper? - In what order do static blocks, instance blocks and constructors run?
Polymorphism: overloading vs overriding
Overloading is resolved by the compiler from argument types; overriding is resolved at run time from the real object's class.
- Compile-time (static) polymorphism = method overloading: same name, different parameter lists. The compiler picks one using the static (declared) types of the arguments.
- Overload lookup goes in phases: exact or widening match first, then boxing/unboxing, then varargs. So
show(5)prefersshow(long)overshow(Integer). - Return type alone cannot overload a method.
- Runtime (dynamic) polymorphism = method overriding: a subclass redefines an inherited instance method. The JVM picks the version from the actual object (dynamic dispatch).
- Fields are not polymorphic:
parentRef.fieldreads the parent's field even if the child declares a field with the same name. staticmethods are hidden, not overridden: the call is bound to the declared type.privateandfinalmethods cannot be overridden either.- Always use
@Overrideso the compiler catches typos and wrong signatures.
Interview questions
- What is polymorphism? Give both kinds.
- Difference between overloading and overriding?
- Can you override a static or private method?
- Why does
show(5)pickshow(long)and notshow(Integer)?
Access modifiers & static vs instance
Access modifiers control who can see a member; static members belong to the class, instance members to each object.
- Java has four access levels:
private, package-private (no keyword),protected,public. Top-level classes can only bepublicor package-private. protected= same package plus subclasses in other packages (through inheritance).- Rule of thumb: make everything as private as possible, widen only when needed.
- A static field has one copy per class. A static method has no
this, so it cannot touch instance fields directly. - A static nested class needs no outer object. An inner class (non-static) holds a hidden reference to its outer object, which can cause memory leaks.
- Static blocks run once when the class is initialised. Good for constants and lookup tables; bad for hidden global state.
Interview questions
- Explain Java's access modifiers.
- Difference between static and instance members?
- Static nested class vs inner class?
Abstract class vs interface
Use an abstract class for a shared base with state; use an interface for a capability that unrelated classes can implement.
- An abstract class cannot be instantiated. It can have fields, constructors, concrete and abstract methods, and any access level.
- An interface is a contract. Since Java 8 it can have
defaultandstaticmethods; since Java 9,privatemethods. Fields are implicitlypublic static final. - A class
extendsone abstract class butimplementsmany interfaces. - Abstract class = is-a with shared code (
BirdforSparrow). Interface = can-do (Flyer,Comparable,Runnable). - Prefer interfaces for public APIs: easier to mock, no lock-in to one hierarchy. Add a skeletal abstract class (like
AbstractList) when implementations share a lot of code. - Java 17+
sealedclasses and interfaces limit which types may implement them, which is useful for closed domain hierarchies.
Interview questions
- Abstract class vs interface: when do you use each?
- Why were default methods added to interfaces?
- Can an abstract class have a constructor? Can an interface?
Relationships & Design Principles
Association, aggregation, composition (UML)
Association = knows/uses; aggregation = has-a but parts live independently; composition = owns, parts die with the whole.
- Association: a general link where one object uses or knows another (
TeacherandStudent). Can be one-way or two-way, with multiplicity (1, 0..1, *). - Aggregation: a weak 'whole–part' or has-a. The part is created outside and can exist without the whole (
DepartmenthasProfessors). UML: hollow diamond ◇ at the whole. - Composition: a strong has-a. The whole creates and owns the parts; parts are not shared and die with it (
HouseandRoom,OrderandOrderLine). UML: filled diamond ◆. - Inheritance (generalisation) is is-a: solid line with a hollow triangle pointing at the parent. Realisation (implements) uses a dashed line.
- Dependency: a short-lived use, such as a method parameter or local variable. Dashed arrow.
- In code, aggregation vs composition is about lifecycle and ownership, not syntax: both are just fields.
Interview questions
- Difference between aggregation and composition?
- What is association?
- How would you show composition in Java code?
Composition over inheritance
Build behaviour by holding and delegating to other objects; inherit only for a true, stable is-a relationship.
- Inheritance is white-box reuse: the child depends on the parent's internals, so parent changes can silently break it (the fragile base class problem).
- Composition is black-box reuse: you hold a reference to another object and call its public API. You can swap it at run time and test it with a fake.
- Deep hierarchies explode:
FlyingSwimmingRobotDuck. With composition you combine small parts (FlyBehaviour,SwimBehaviour). - Use inheritance when the child truly is-a parent everywhere (LSP holds), the parent is designed for extension, and you control both.
- Many patterns are composition in action: Strategy, Decorator, Proxy, State, Adapter.
- Kotlin's
bydelegation and Java records plus interfaces make composition cheap to write.
Interview questions
- Why favour composition over inheritance?
- What is the fragile base class problem?
- When is inheritance the right choice?
Multiple inheritance & the diamond problem
When two parents share a grandparent and both override a method, which one wins? Each language answers differently.
- The diamond problem:
BandCboth extendAand overridem();Dextends both. A call toD.m()is ambiguous, and in C++Dmay even hold two copies ofA's fields. - Java forbids multiple class inheritance. Interfaces can be multiple because they carry no instance state.
- Java default-method rules: (1) a class method wins over any interface default; (2) the more specific interface wins (sub-interface over super-interface); (3) otherwise it is a compile error and you must override, optionally calling
X.super.m(). - C++ allows multiple inheritance. Use
virtualbase classes to share one copy of the grandparent, and qualify calls (B::m()) to resolve ambiguity. - Python allows it and resolves calls with the C3 linearisation (MRO).
super()follows the MRO, not just the direct parent, enabling cooperative mixins. - C# is like Java (single class, multiple interfaces, default interface methods since C# 8). Go has no inheritance at all, only embedding and interfaces.
Interview questions
- What is the diamond problem and how does Java avoid it?
- Two interfaces have the same default method. What happens?
- How does Python resolve multiple inheritance?
Coupling, cohesion, LoD, DRY/KISS/YAGNI
Aim for classes that do one focused job (high cohesion) and know little about each other (low coupling).
- Cohesion: how closely the parts of one class belong together. High cohesion = one focused purpose.
UserServicethat also sends emails and builds PDFs has low cohesion. - Coupling: how much one class depends on another's details. Low coupling = depend on small interfaces, not concrete classes or internals.
- Law of Demeter (principle of least knowledge): a method should call only its own object, its parameters, objects it creates, and its fields. Avoid
order.getCustomer().getWallet().debit()train wrecks. Tell, don't ask. - DRY (Don't Repeat Yourself): every piece of knowledge has one source of truth. It is about duplicated knowledge, not similar-looking code.
- KISS (Keep It Simple): pick the simplest design that works. YAGNI (You Aren't Gonna Need It): do not build for imagined future needs.
- These pull against each other: over-DRY creates wrong abstractions; strict YAGNI can skip a cheap extension point. Explain the trade-off.
Interview questions
- What are coupling and cohesion? Which do you want?
- What is the Law of Demeter?
- Explain DRY, KISS and YAGNI.
SOLID Principles
SRP & Open/Closed
SRP: a class should have one reason to change. OCP: add new behaviour by adding code, not by editing tested code.
- Single Responsibility Principle: a module should be responsible to one actor (one reason to change). Tax rules, report layout and storage change for different people, so they belong in different classes.
- SRP does not mean 'one method per class'. It means one cohesive responsibility.
- Open/Closed Principle: software should be open for extension, closed for modification. New cases plug in through an abstraction instead of editing a growing
if/switch. - OCP tools: interfaces + polymorphism, Strategy, Decorator, plugins, a registry
Map<String, Handler>. - Apply OCP where change is likely (payment methods, discount rules). Do not abstract everything up front (YAGNI).
- Java 21 sealed types + exhaustive
switchare a deliberate alternative: closed set of types, and the compiler flags every switch to update.
Interview questions
- Explain the Single Responsibility Principle with an example.
- What is the Open/Closed Principle?
- Does OCP mean you never modify a class?
Liskov Substitution (square/rectangle)
A subtype must be usable anywhere its parent is expected, without the caller noticing a change in behaviour.
- LSP (Barbara Liskov): if
Sis a subtype ofT, code written forTmust keep working with anS. Subtyping is about behaviour, not only method signatures. - Contract rules: a subtype may not strengthen preconditions (accept less), may not weaken postconditions (promise less), and must keep the parent's invariants.
- Classic violation:
Square extends Rectangle. Setting width then height on a square gives an area the caller did not expect. - Other smells: overrides that throw
UnsupportedOperationException,instanceofchecks on subtypes, empty overrides that do nothing. - Fixes: model both as separate immutable types under a common
Shape, use composition, or split the interface so each type only promises what it can do. - Real JDK example:
Collections.unmodifiableListreturns aListwhoseaddthrows, a known compromise documented as an 'optional operation'.
Interview questions
- What is the Liskov Substitution Principle?
- Why does
Square extends Rectangleviolate LSP? - How do you fix the square/rectangle problem?
Interface Segregation & Dependency Inversion
ISP: many small client-focused interfaces beat one fat one. DIP: high-level policy and low-level details both depend on abstractions.
- ISP: no client should be forced to depend on methods it does not use. Split a fat
Machine { print; scan; fax }intoPrinter,Scanner,Fax. - Signs of a fat interface: implementers throwing
UnsupportedOperationException, empty method bodies, clients recompiled for changes they don't care about. - DIP: (1) high-level modules should not depend on low-level modules; both depend on abstractions. (2) abstractions should not depend on details.
- In practice the high-level layer owns the interface (
Notifier), and the infrastructure (EmailNotifier) implements it. The dependency arrow now points toward the business logic. - Dependency injection (constructor injection) is the usual way to apply DIP. Spring, Guice and Dagger automate the wiring, but plain constructors work too.
- DIP ≠ DI ≠ IoC: DIP is the design principle, DI is the technique of passing dependencies in, Inversion of Control is the broader idea of a framework calling your code.
Interview questions
- Explain the Interface Segregation Principle.
- Explain the Dependency Inversion Principle.
- Difference between DIP, DI and IoC?
- Why is constructor injection preferred over field injection?
Design Patterns
Singleton (thread-safe & enum)
Ensures one instance with a global access point; in Java prefer the enum or holder idiom, and use DCL only with volatile.
- Parts: a
privateconstructor, astaticfield holding the instance, astaticaccessor. - Eager:
static final INSTANCE = new X(). Simple and thread-safe (class init is locked by the JVM), but created even if unused. - Synchronized lazy getter: safe but takes a lock on every call.
- Double-checked locking (DCL): check, lock, check again. The field must be
volatile, otherwise another thread may see a half-constructed object. - Holder idiom (initialisation-on-demand): a nested static class holds the instance; the JVM loads it lazily and thread-safely on first use. No locks in your code.
- Enum singleton:
enum Config { INSTANCE; }. Thread-safe, and the JVM prevents extra instances through reflection and serialization. Effective Java recommends it. - Downsides: hidden global state, hard to mock, hides dependencies. Prefer one instance managed by a DI container (Spring beans are singleton-scoped by default).
Interview questions
- How do you write a thread-safe singleton in Java?
- Why does double-checked locking need
volatile? - How can a singleton be broken?
- Why is Singleton often called an anti-pattern?
Factory, Abstract Factory, Builder, Prototype
Creational patterns hide how objects are created, so callers depend on types and intent rather than concrete constructors.
- Simple / static factory: one method picks and returns an implementation (
List.of,Notification.of("sms")). Not a GoF pattern, but the most common. - Factory Method: a superclass defines the algorithm and an abstract
createX(); subclasses decide which class to create. Uses inheritance. - Abstract Factory: an object that creates a family of related products (dark button + dark checkbox) so they always match. Uses composition.
- Builder: constructs complex objects step by step with readable, named setters; validates in
build()and returns an immutable object. Fixes the telescoping constructor problem. - Prototype: create new objects by copying an existing configured one. In Java prefer a copy constructor or
copy()method overCloneable/clone(), which is shallow and awkward. - Choose: one product, varies by input → static factory; framework hook → Factory Method; matching families → Abstract Factory; many optional params → Builder; expensive setup to copy → Prototype.
Interview questions
- Difference between Factory Method and Abstract Factory?
- When would you use the Builder pattern?
- What is the Prototype pattern? Why avoid
Cloneable? - What advantages do static factory methods have over constructors?
Adapter, Decorator, Facade, Proxy, Composite
Structural patterns combine objects: convert an interface (Adapter), add behaviour (Decorator), simplify (Facade), control access (Proxy), or build trees (Composite).
- Adapter: wraps an existing class so it fits the interface the client expects. Used for legacy or third-party code you cannot change.
- Decorator: wraps an object with the same interface to add behaviour; wrappers can be stacked at run time.
new BufferedReader(new InputStreamReader(in)). - Facade: one simple entry point to a complex subsystem (
HomeTheater.watch()hides amp, projector, lights). It does not stop direct access to the subsystem. - Proxy: same interface, controls access to the real object: lazy loading (virtual proxy), security, caching, remote calls, logging. Spring AOP and
@Transactionalwork through proxies. - Composite: tree of objects where leaves and groups share one interface, so clients treat a single file and a folder the same (
size()). - Adapter vs Decorator vs Proxy: Adapter changes the interface; Decorator keeps it and adds features; Proxy keeps it and controls access.
Interview questions
- Difference between Adapter, Decorator and Proxy?
- What is the Facade pattern? Is it the same as an API gateway?
- Where is the Decorator pattern used in the JDK?
- Explain the Composite pattern with an example.
Strategy, Observer, Command, Template, State, CoR, Iterator
Behavioural patterns decide how objects share work and communicate: swap algorithms, broadcast events, wrap requests, fix skeletons, change by state, pass along chains, walk collections.
- Strategy: a family of interchangeable algorithms behind one interface, chosen at run time (
Comparator, pricing rules). In modern Java, often just a lambda. - Observer: a subject keeps a list of subscribers and notifies them on change (event listeners, pub/sub). Watch out for memory leaks from forgotten subscriptions.
- Command: a request as an object with
execute()(and oftenundo()). Enables queues, logs, retries, undo/redo, macros.Runnableis a command. - Template Method: a
finalmethod in a base class fixes the steps; subclasses fill some steps or hooks. Inheritance-based (HttpServlet.service→doGet). - State: an object changes behaviour when its internal state changes, by delegating to a state object instead of big
if (status == ...)blocks. - Chain of Responsibility: a request passes through handlers until one handles it or the chain ends (servlet filters, Spring Security filter chain, middleware).
- Iterator: walk a collection without exposing its structure (
Iterable/Iterator, enhanced for-loop).
Interview questions
- Difference between Strategy and Template Method?
- Difference between Strategy and State?
- Explain the Observer pattern and its pitfalls.
- How would you implement undo/redo?
Advanced Design & LLD
Choosing a pattern & anti-patterns
Pick a pattern from the problem you hear in the requirements, and recognise the anti-patterns that make code hard to change.
- Start from the pain, not the pattern. Name the force: 'many if/else on type', 'object creation is messy', 'need to add behaviour without touching class'.
- God object: one class that knows and does everything (
AppManagerwith 4,000 lines). Low cohesion, high coupling, merge conflicts. Fix by extracting classes per responsibility. - Anemic domain model: entities are getter/setter bags and all rules live in services. Rules get duplicated and invariants are not enforced. Fix by moving behaviour into the entity.
- Other anti-patterns: Singleton abuse (global state), golden hammer (one pattern everywhere), spaghetti code, primitive obsession (strings for money/emails), deep inheritance (yo-yo problem), lava flow (dead code nobody dares delete).
- Patterns add indirection. If the variation is not real, the pattern is over-engineering (KISS/YAGNI).
Interview questions
- What is a God object and how do you fix it?
- What is an anemic domain model?
- How do you choose a design pattern in an interview?
- Can overusing patterns be harmful?
Immutability, equals & hashCode
Immutable objects are simpler and thread-safe; if you override equals, you must override hashCode consistently.
- Immutable class recipe:
finalclass (or private constructor), all fieldsprivate final, no setters, validate in the constructor, defensive copies of mutable inputs and outputs, return new objects for changes ('withers'). - Benefits: thread-safe without locks, safe as map keys and set members, easy to cache and share, no defensive copying by callers.
equalscontract: reflexive, symmetric, transitive, consistent, andx.equals(null)is false.hashCodecontract: equal objects must have equal hash codes. Unequal objects may collide. Break this andHashMap/HashSetlose objects.- Use the same fields in
equalsandhashCode. Prefer immutable fields; a key whose hash changes after insertion becomes unreachable. - Java records generate
equals,hashCodeandtoStringfrom all components and are shallowly immutable (aListcomponent can still be mutated unless copied). equalswith inheritance is hard:instanceofcan break symmetry with subclasses adding fields;getClass()breaks LSP. Prefer composition orfinalvalue classes.
Interview questions
- How do you make a class immutable in Java?
- Why must you override hashCode when you override equals?
- What happens if a key's fields change after it is put in a HashMap?
- What are the benefits of immutable objects?
LLD interview approach: parking lot & library
Clarify, find entities and relationships, draw a small class diagram, code the core flow, then discuss concurrency and extensions.
- 1. Clarify requirements (3–5 min): actors, main use cases, scale, what is out of scope. Write them down as a short list.
- 2. Identify entities: nouns become classes or enums (
ParkingLot,Spot,Vehicle,Ticket); verbs become methods (park,unpark,pay). - 3. Relationships and diagram: composition (lot ◆ spots), association (ticket → vehicle), interfaces for parts likely to vary (
PricingStrategy). - 4. Apply patterns only where they fit: Strategy for pricing or spot allocation, Factory for vehicles, State for ticket/order status, Observer for display boards, Singleton (or one DI bean) for the lot.
- 5. Code the core flow with clean names, enums and immutability. Show SOLID choices out loud.
- 6. Discuss edge cases: concurrency (two cars, one spot → lock or atomic claim), lot full, lost ticket, payment failure, extensibility (EV charging, multiple floors).
- Library system sketch:
Library◆BookItem(copies) →Book(title/ISBN);Memberborrows viaLoan(dates, fine);FinePolicystrategy;Reservationqueue; Observer notifies members when a reserved book returns.
Interview questions
- How do you approach a low-level design interview?
- Design a parking lot: what are the main classes?
- How do you handle concurrency when two cars try to take the last spot?
- Sketch a library management system.
- How do you make your design extensible?