Bird
Raised Fist0

If you want to add a new behavior 'canFly' only to Bird, what happens if you use inheritance to add this behavior in the base class?

easy🧠🧾 Concept Trace Q3 of Q15
OOP & Design Patterns - Composition vs Inheritance - Favour Composition, Why & When
Consider a class hierarchy where a base class Animal has subclasses Dog and Bird. If you want to add a new behavior 'canFly' only to Bird, what happens if you use inheritance to add this behavior in the base class?
AOnly Bird will have 'canFly' because subclasses inherit selectively.
BAll animals will have the 'canFly' behavior, even if it doesn't apply.
CDog will override 'canFly' to false automatically.
DThe base class cannot have behaviors; only subclasses can.
Step-by-Step Solution
Solution:
  1. Step 1: Understand inheritance behavior propagation

    All subclasses inherit base class members unless explicitly overridden.
  2. Step 2: Adding 'canFly' in base class affects all subclasses

    Dog will also have 'canFly' property, which is semantically incorrect.
  3. Step 3: Evaluate other options

    Subclasses do not inherit selectively; overriding is manual; base classes can have behaviors.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Inheritance propagates base class behavior to all subclasses [OK]
Quick Trick: Inheritance shares base behavior with all subclasses by default [OK]
Common Mistakes:
MISTAKES
  • Assuming subclasses inherit only relevant behaviors
  • Believing base classes cannot have behaviors
Trap Explanation:
PITFALL
  • Candidates often think inheritance is selective or that base classes are abstract without behavior.
Interviewer Note:
CONTEXT
  • Checks understanding of inheritance propagation and its pitfalls.
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