Bird
Raised Fist0

Design Stack Overflow in OOP - Question, Answer, Vote, Tag, Reputation, Bounty

LLDmediumInterview freq: high
Choose your preparation mode4 modes available
▶
Class Trace
Step 1/4
Post abstract class

Post is an abstract class holding shared state like id, content, and author, which interfaces cannot hold in Java.

🎯 Tests whether candidate knows abstract class is correct because Post has shared instance state and behavior that interfaces cannot hold in Java.
public abstract class Post {
    protected long id;
    protected String content;
    protected User author;
    
    public void editContent(String newContent) {
        this.content = newContent;
    }
    
    public abstract int getScore();
}
User composition with Posts

User has a composition relationship with Posts, meaning Posts cannot exist without their User owner, enforcing lifecycle ownership.

🎯 Tests if candidate understands composition in Java means User owns Posts lifecycle and must manage their creation and deletion.
public class User {
    private long id;
    private int reputation;
    private List<Post> posts = new ArrayList<>();
    
    public void addPost(Post p) {
        posts.add(p);
    }
    
    public synchronized void addReputation(int points) {
        this.reputation += points;
    }
}
Vote association with User and Post

Vote has association relationships with User and Post, indicating independent lifecycles and no ownership, allowing votes to exist independently.

🎯 Tests if candidate distinguishes association from composition and knows Vote references User and Post without owning them.
public class Vote {
    private User voter;
    private Post post;
    private int value; // +1 or -1
    
    public Vote(User voter, Post post, int value) {
        this.voter = voter;
        this.post = post;
        this.value = value;
    }
    
    public void castVote() {
        // logic to apply vote
    }
}
Bounty specialization

Bounty is a separate class associated with Question to represent a special reward, showing realization of specialization without modifying Post hierarchy.

🎯 Tests if candidate applies Single Responsibility Principle by separating Bounty as a class and associates it with Question rather than extending Post.
public class Bounty {
    private int amount;
    private Date expiryDate;
    
    public boolean isActive() {
        return new Date().before(expiryDate);
    }
}
📐
Class Diagram
Class Diagram
       +----------------+
       | <<Abstract>>   |
       | Post           |
       +----------------+
       | -id: long      |
       | -content: String|
       | -author: User  |
       +----------------+
       | +editContent() |
       | +getScore()    |
       +----------------+
              │ extends
       +----------------+
       | Question       |
       +----------------+
       | -tags: List<Tag>|
       | -bounty: Bounty|
       +----------------+
       | +addTag(Tag)   |
       | +setBounty()   |
       +----------------+
              │ extends
       +----------------+
       | Answer         |
       +----------------+
       | -question:Question|
       +----------------+
       | +markAccepted() |
       +----------------+
       
       +----------------+
       | User           |
       +----------------+
       | -id: long      |
       | -reputation: int|
       +----------------+
       | +addReputation()|
       +----------------+
              ◆ composition
              Post[] posts
       
       +----------------+
       | Vote           |
       +----------------+
       | -voter: User   |
       | -post: Post    |
       | -value: int    |
       +----------------+
       | +castVote()    |
       +----------------+
              ──► association
              User and Post independent lifecycles
       
       +----------------+
       | Bounty         |
       +----------------+
       | -amount: int   |
       | -expiryDate: Date|
       +----------------+
       | +isActive()    |
       +----------------+

This class diagram uses an abstract Post class to hold shared state and behavior for Question and Answer, leveraging Java's abstract class capability to hold instance fields. User composes Posts, enforcing strong lifecycle ownership, so Posts cannot exist without their User. Vote is associated with User and Post, reflecting independent lifecycles and avoiding ownership, which fits the association relationship in Java. Bounty is a separate class linked to Question, following the Single Responsibility Principle by separating concerns and avoiding bloating the Post hierarchy. These design decisions demonstrate Java-specific OOP principles like abstract classes for shared state, composition for lifecycle management, and association for loose coupling.

Primary Focus

✓ Abstract class inheritance + Composition lifecycle + Association vs Composition + Realization of specialization

Practice

(1/5)
1. In designing a plugin interface in Java, should the Plugin be an abstract class or an interface if plugins must maintain internal state and provide default lifecycle methods? Why?
easy
A. Interface, because it allows multiple inheritance and enforces method signatures without state.
B. Interface, because Java interfaces can now have private fields for state.
C. Abstract class, because it can hold shared state and provide default method implementations.
D. Abstract class, because it forces all plugins to share the same constructor signature.

Solution

  1. Step 1: Analyze state and default lifecycle method needs

    Interfaces cannot hold instance state; abstract classes can hold fields and provide default method bodies.
  2. Step 2: Determine which construct fits stateful plugins with default behavior

    Abstract class fits because it supports shared state and default lifecycle implementations, easing plugin development.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Abstract class supports state and default methods [check]
Hint: State + default methods = abstract class, not interface [check]
Common Mistakes:
2. In the Social Media Profile System, the User class has a private constructor and a static synchronized getInstance() method to manage user sessions. Which design pattern is applied here and why is this the correct choice?
easy
A. Singleton Pattern, ensuring only one instance manages user sessions globally.
B. Factory Pattern, because it creates objects without exposing instantiation logic.
C. Builder Pattern, to construct complex User objects step-by-step.
D. Prototype Pattern, to clone existing User instances efficiently.

Solution

  1. Step 1: Identify the pattern from constructor and method

    The private constructor prevents external instantiation, and the static synchronized getInstance() method controls instance creation, which matches Singleton pattern characteristics.
  2. Step 2: Why Singleton fits user session management

    Singleton ensures a single global instance manages user sessions, avoiding multiple conflicting session managers.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Private constructor + static synchronized getInstance() -> Singleton [check]
Hint: Private constructor + static getInstance() -> Singleton [check]
Common Mistakes:
3. In a multi-threaded Java Observer implementation, if notifyObservers() is not synchronized, which exact sequence of events can cause observers to receive inconsistent or duplicate updates?
medium
A. Thread 1 checks observer list size -> 3, context switch; Thread 2 removes an observer -> size 2; Thread 1 continues notifying 3 observers, causing duplicate notifications.
B. Thread 1 calls notifyObservers(), Thread 2 waits until Thread 1 finishes, then calls notifyObservers().
C. Thread 1 and Thread 2 both add observers simultaneously, causing a ConcurrentModificationException during notification.
D. Thread 1 updates subject state, Thread 2 reads old state before notification, causing stale data delivery.

Solution

  1. Step 1: Identify race condition in notifyObservers()

    Without synchronization, Thread 1 reads observer list size as 3, then context switches.
  2. Step 2: Thread 2 modifies observer list by removing one observer, reducing size to 2.

    Thread 1 resumes and tries to notify 3 observers, causing out-of-date or duplicate notifications.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Unsynchronized notifyObservers() -> stale observer list read -> inconsistent notifications [check]
Hint: Unsynchronized notify reads stale observer list -> duplicate notifications [check]
Common Mistakes:
4. In a parking lot system using the Strategy pattern, if parkVehicle() is NOT synchronized, which exact thread interleaving causes double-booking of the same spot?
medium
A. Thread 1 parks vehicle; Thread 2 waits until Thread 1 finishes, then parks another vehicle.
B. Thread 1 checks spot availability -> true, context switch; Thread 2 checks spot availability -> true; both park simultaneously.
C. Thread 1 parks vehicle; Thread 2 reads spot as occupied and waits.
D. Thread 1 and Thread 2 both crash due to deadlock.

Solution

  1. Step 1: Identify check-then-act race condition

    Without synchronization, Thread 1 reads spot as available but before marking it occupied, context switches to Thread 2 which also reads available.
  2. Step 2: Both threads proceed to park, causing double-booking

    Because the state update is not atomic, both threads believe the spot is free and park simultaneously.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Check-then-act gap -> double-booking due to unsynchronized parkVehicle() [check]
Hint: Check availability -> context switch -> both park -> double-booking [check]
Common Mistakes:
5. To support ElectricCar jobs requiring ChargingSpot resources in the Job Scheduler, what is the minimum change to the current design to maintain extensibility without modifying existing classes?
hard
A. Create a new GodClass managing both ElectricCar and ChargingSpot logic, bypassing existing abstractions.
B. Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility map externally.
C. Modify VehicleType enum to include ElectricCar and add charging logic inside existing Vehicle class.
D. Add charging logic directly inside Job class and modify existing Spot classes to handle ElectricCar.

Solution

  1. Step 1: Identify extensibility requirements

    ElectricCar and ChargingSpot are new types requiring minimal impact on existing Vehicle and Spot classes.
  2. Step 2: Apply extensibility without modifying existing classes

    Add new enum values for types, create ElectricCar subclass, and update SpotCompatibility map externally to maintain OCP and avoid class explosion.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    New enums + subclass + external compatibility update -> minimal existing code change [check]
Hint: Add new enums + subclass + external map update -> minimal change [check]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard