Bird
Raised Fist0

When a bus arrives, which sequence of method calls correctly determines if a suitable spot is available, assuming polymorphism is used?

medium🧠🧾 Concept Trace Q4 of Q15
OOP & Design Patterns - Design a Parking Lot - LLD with OOP (Classes, Patterns, Extensibility)
Consider a parking lot system where vehicles of different sizes (motorcycle, car, bus) are modeled using inheritance. When a bus arrives, which sequence of method calls correctly determines if a suitable spot is available, assuming polymorphism is used?
ACall ParkingSpot.canFitVehicle() which uses instanceof checks to identify vehicle type
BCall Bus-specific method isSpotLargeEnough() bypassing polymorphism
CCall Vehicle.getSize() and compare with spot size externally in the controller
DCall Vehicle.canFitInSpot() overridden by Bus, which checks if the spot size fits a bus
Step-by-Step Solution
Solution:
  1. Step 1: Understand polymorphism in inheritance

    Vehicle subclasses override canFitInSpot() to provide specific logic.
  2. Step 2: Evaluate method call sequences

    Calling Vehicle.canFitInSpot() on a Bus instance invokes Bus's override, leveraging polymorphism.
  3. Step 3: Analyze other options

    Using instanceof (A) breaks OOP principles; external size comparison (C) violates encapsulation; Bus-specific method (D) bypasses polymorphism.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Polymorphism enables dynamic method dispatch [OK]
Quick Trick: Polymorphism calls subclass overrides automatically [OK]
Common Mistakes:
MISTAKES
  • Using instanceof checks instead of polymorphism
  • Comparing sizes externally breaking encapsulation
  • Bypassing polymorphism with subclass-specific calls
Trap Explanation:
PITFALL
  • Candidates often misuse instanceof or external logic instead of relying on polymorphism.
Interviewer Note:
CONTEXT
  • Assesses understanding of inheritance and polymorphism in design.
Master "Design a Parking Lot - LLD with OOP (Classes, Patterns, Extensibility)" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes