Bird
Raised Fist0

The 4 OOP Pillars with Interview Examples - Encapsulation, Abstraction, Inheritance, Polymorphism

LLDeasyInterview freq: high
Choose your preparation mode4 modes available
▶
Class Trace
Step 1/4
AbstractShape and Circle inheritance

AbstractShape is an abstract class holding shared state 'color' and abstract methods draw() and area(). Circle extends AbstractShape and implements these methods.

🎯 Tests whether candidate knows abstract class is used because it holds instance state 'color' which interfaces cannot hold in Java, enforcing Abstraction and Inheritance pillars.
public abstract class AbstractShape {
    protected String color;
    public abstract void draw();
    public abstract double area();
}
EncapsulatedClass encapsulation

EncapsulatedClass hides its 'data' field with private access and exposes public getter and setter methods to control access.

🎯 Tests understanding of Encapsulation pillar by enforcing private field with public synchronized accessors if needed for thread safety.
public class EncapsulatedClass {
    private int data;
    public int getData() { return data; }
    public void setData(int data) { this.data = data; }
}
PolymorphicPrinter polymorphism

PolymorphicPrinter defines a print(Object) method that can accept any object and invoke overridden toString() methods, demonstrating runtime polymorphism.

🎯 Tests Polymorphism pillar by verifying candidate understands method overriding and dynamic dispatch in Java.
public class PolymorphicPrinter {
    public void print(Object obj) {
        System.out.println(obj.toString());
    }
}
Vehicle abstract class with volatile and synchronized

Vehicle is an abstract class with shared state 'licensePlate' and a volatile boolean 'isAvailable'. Methods startEngine() and stopEngine() are synchronized to ensure thread-safe state changes.

🎯 Tests candidate's knowledge of volatile keyword to prevent stale reads and synchronized methods to atomically modify shared state, enforcing thread safety in Java.
public abstract class Vehicle {
    protected String licensePlate;
    protected volatile boolean isAvailable;
    public synchronized void startEngine() {
        if (!isAvailable) {
            isAvailable = true;
        }
    }
    public synchronized void stopEngine() {
        if (isAvailable) {
            isAvailable = false;
        }
    }
}
📐
Class Diagram
Class Diagram
       +----------------------+
       | <<Abstract>>         |
       | AbstractShape        |
       +----------------------+
       | - color: String      |
       +----------------------+
       | + draw(): void       |
       | + area(): double     |
       +----------------------+
               │ extends
       +----------------------+
       | Circle               |
       +----------------------+
       | - radius: double     |
       +----------------------+
       | + draw(): void       |
       | + area(): double     |
       +----------------------+

       +----------------------+
       | EncapsulatedClass    |
       +----------------------+
       | - data: int          |
       +----------------------+
       | + getData(): int     |
       | + setData(int): void |
       +----------------------+

       +----------------------+
       | PolymorphicPrinter   |
       +----------------------+
       |                      |
       +----------------------+
       | + print(Object): void|
       +----------------------+

       +----------------------+
       | <<Abstract>>         |
       | Vehicle              |
       +----------------------+
       | - licensePlate: String|
       | - isAvailable: volatile bool |
       +----------------------+
       | + startEngine(): void [sync]|
       | + stopEngine(): void  [sync]|
       +----------------------+

This class diagram illustrates four key Java OOP pillars with concrete examples. AbstractShape is an abstract class holding shared state 'color' and abstract methods, demonstrating Abstraction and Inheritance. Circle extends it, implementing the abstract methods. EncapsulatedClass shows Encapsulation by hiding its 'data' field and exposing controlled accessors. PolymorphicPrinter exemplifies Polymorphism by printing any object's overridden toString(), showcasing dynamic dispatch. Vehicle is an abstract class with volatile and synchronized methods to ensure thread-safe state changes, highlighting Java concurrency mechanisms. The diagram uses inheritance and composition relationships with clear stereotypes, emphasizing SOLID principles and Java-specific concurrency constructs.

Primary Focus

✓ Abstract class vs Interface + Composition lifecycle + Polymorphism via method overriding + Template Method pattern

Practice

(1/5)
1. The brokerage system currently calculates fees using a FeeCalculator class. To add a new WeekendFeeStrategy without modifying existing code, which SOLID principle applies and what is the minimum change required?
medium
A. Open/Closed Principle: Create a new WeekendFeeStrategy class implementing FeeStrategy interface; FeeCalculator uses polymorphism.
B. Single Responsibility Principle: Modify FeeCalculator to handle weekend fees explicitly.
C. Dependency Inversion Principle: Inject concrete WeekendFeeStrategy directly into FeeCalculator constructor.
D. Liskov Substitution Principle: Replace FeeCalculator with WeekendFeeCalculator subclass overriding fee logic.

Solution

  1. Step 1: Identify the SOLID principle for extensibility

    Open/Closed Principle (OCP) states software entities should be open for extension but closed for modification.
  2. Step 2: How to apply OCP here

    Create a new class WeekendFeeStrategy implementing FeeStrategy interface; FeeCalculator uses polymorphism to apply different strategies without modification.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    New strategy class + polymorphism -> OCP compliance [check]
Hint: Add new fee strategy class, no FeeCalculator changes [check]
Common Mistakes:
2. In a parking system, the parkVehicle() method checks if a spot is available and then marks it occupied. Without synchronization, which exact thread interleaving causes double-booking of the same spot?
medium
A. Thread 1 reads spot as occupied; Thread 2 waits until spot is free.
B. Thread 1 checks spot availability -> true, context switch before marking occupied; Thread 2 checks availability -> true, both mark spot occupied.
C. Thread 1 marks spot occupied; Thread 2 reads spot as occupied and aborts parking.
D. Thread 1 and Thread 2 both wait on a lock, preventing double-booking.

Solution

  1. Step 1: Trace parkVehicle() check-then-act sequence

    Thread 1 reads spot as available (true), then context switch occurs before marking occupied.
  2. Step 2: Thread 2 also reads spot as available (true) and proceeds to mark it occupied, causing double-booking.

  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Check-then-act race without synchronization -> double-booking [check]
Hint: Check-then-act gap causes double-booking without synchronized [check]
Common Mistakes:
3. In a parking lot system, the parkVehicle() method checks if a spot is available and then marks it occupied. Without synchronized, what exact thread interleaving causes double-booking?
medium
A. Thread 1 parks vehicle, Thread 2 waits until Thread 1 finishes, then parks.
B. Thread 1 checks spot availability -> true, context switch; Thread 2 checks availability -> true; both mark spot occupied.
C. Thread 1 marks spot occupied, Thread 2 checks availability -> false, no double-booking.
D. Thread 1 and Thread 2 both crash simultaneously causing no booking.

Solution

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

    Without synchronization, Thread 1 reads spot as available but before marking occupied, context switches to Thread 2 which also reads available.
  2. Step 2: Both threads proceed to mark the spot occupied independently

    This leads to double-booking as both think the spot was free at check time.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Check-then-act gap -> both threads see available -> double-booking [check]
Hint: Check-then-act without sync -> double-booking race [check]
Common Mistakes:
4. In a parking lot system, if parkVehicle() is not synchronized, which exact thread interleaving causes double-booking of the same spot?
medium
A. Thread 1 parks vehicle, Thread 2 parks vehicle simultaneously without checking availability.
B. Thread 1 updates spot status after parking, Thread 2 reads stale status and parks again.
C. Thread 1 releases spot, Thread 2 immediately parks without synchronization.
D. Thread 1 checks spot availability -> true, context switch; Thread 2 checks availability -> true; both park concurrently.

Solution

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

    Without synchronization, Thread 1 reads spot as available and is preempted before marking it occupied. Thread 2 also reads available and proceeds to park.
  2. Step 2: Confirm both threads park concurrently causing double-booking

    Both threads believe the spot is free and park, leading to inconsistent state and double-booking.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Unsynchronized check-then-act -> double-booking race [check]
Hint: Check-then-act without sync -> double-booking race condition [check]
Common Mistakes:
5. You need to add support for ElectricCar and ChargingSpot in an existing parking system using Observer pattern. What is the minimum change to the current design to support this without modifying existing classes?
hard
A. Add a boolean isElectric flag to Vehicle and Spot classes and update existing logic to handle charging spots.
B. Modify Vehicle and Spot classes to include electric-specific fields and logic for charging compatibility.
C. Create a new ElectricCar class and ChargingSpot class, then modify the Subject to notify these new types explicitly.
D. Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility map externally.

Solution

  1. Step 1: Identify extensibility requirements

    Adding ElectricCar and ChargingSpot should not modify existing classes to respect OCP.
  2. Step 2: Evaluate options

    Modify Vehicle and Spot classes to include electric-specific fields and logic for charging compatibility. and D modify existing classes, violating OCP; Create a new ElectricCar class and ChargingSpot class, then modify the Subject to notify these new types explicitly. modifies Subject, increasing coupling.
  3. Step 3: Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility map externally. adds new enum values and subclasses, updating compatibility externally, preserving existing class integrity.

  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    New enums and subclasses added externally -> existing classes unchanged [check]
Hint: Add enums and subclasses externally, keep existing classes untouched [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