Bird
Raised Fist0

Which design approach best supports adding new capabilities like flying or floating without modifying existing vehicle classes?

easy🔍 Pattern Recognition Q11 of Q15
OOP & Design Patterns - Composition vs Inheritance - Favour Composition, Why & When
You are designing a system for different types of vehicles where some can fly and some can float on water. Which design approach best supports adding new capabilities like flying or floating without modifying existing vehicle classes?
AUse inheritance to create subclasses like FlyingCar and FloatingCar from Vehicle
BUse a single Vehicle class with flags indicating if it can fly or float
CUse composition by creating separate capability classes like FlyBehavior and FloatBehavior and compose them with Vehicle
DUse inheritance and override methods in each subclass to add flying or floating behavior
Step-by-Step Solution
  1. Step 1: Identify the problem with inheritance here

    Inheritance leads to a combinatorial explosion of subclasses (FlyingCar, FloatingCar, FlyingFloatingCar), making the design rigid and hard to maintain.
  2. Step 2: Understand composition benefits

    Composition allows attaching behaviors dynamically via separate classes (FlyBehavior, FloatBehavior), promoting flexibility and easier extension.
  3. Step 3: Analyze other options

    Options A and C rely on inheritance, causing tight coupling and poor scalability. Use a single Vehicle class with flags indicating if it can fly or float uses flags, which leads to complex conditional logic and violates single responsibility.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Composition supports adding new capabilities without modifying existing classes, enhancing maintainability and flexibility.
Quick Trick: Composition lets you add capabilities by combining behaviors, inheritance forces rigid hierarchies.
Common Mistakes:
MISTAKES
  • Assuming inheritance is always better for code reuse
  • Using flags instead of behaviors leads to messy conditionals
Trap Explanation:
PITFALL
  • Inheritance seems simpler but leads to rigid, brittle designs when behaviors multiply; flags seem easy but cause complex conditional logic.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to recognize when composition is preferable over inheritance for flexible design.
Master "Composition vs Inheritance - Favour Composition, Why & When" 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