Bird
Raised Fist0

Which abstraction mechanism is most appropriate to enforce this contract?

easy🔍 Pattern Recognition Q11 of Q15
OOP & Design Patterns - Abstraction - Abstract Class vs Interface - When to Use Which
You are designing a system where multiple unrelated classes must guarantee implementation of certain methods but share no common code. Which abstraction mechanism is most appropriate to enforce this contract?
AUse an abstract class to define the methods and provide partial implementation.
BUse an abstract class only if all classes share a common ancestor.
CUse a concrete class and rely on inheritance for code reuse.
DUse an interface to declare the methods without any implementation.
Step-by-Step Solution
  1. Step 1: Identify the need for a contract without shared code

    Interfaces define method signatures without implementation, perfect for unrelated classes needing a common contract.
  2. Step 2: Why abstract classes are less suitable here

    Abstract classes provide partial implementation and require a common ancestor, which unrelated classes lack.
  3. Step 3: Why concrete classes and inheritance don't fit

    Concrete classes imply implementation and inheritance assumes a hierarchy, which is not guaranteed.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Interfaces enforce contracts without imposing inheritance or shared code.
Quick Trick: Use interfaces when only a contract is needed, abstract classes when sharing code.
Common Mistakes:
MISTAKES
  • Assuming abstract classes are always better for abstraction.
  • Confusing contract enforcement with code reuse.
  • Believing unrelated classes can share an abstract class.
Trap Explanation:
PITFALL
  • Options A and D tempt candidates who think abstraction always means partial implementation or inheritance. Option C confuses concrete classes with abstraction.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to choose between interface and abstract class based on design needs.
Master "Abstraction - Abstract Class vs Interface - When to Use Which" 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