beginnerOOP Recap & UML

When designing two related classes, how do you decide whether to use inheritance or composition?

Use inheritance when the relationship is a genuine, unconditional "is-a" and the subclass needs to reuse the parent's actual implementation and state — for example, a CreditCard genuinely is a Card and shares its fields. Use composition when one class merely needs to use another's capability without being a specialized version of it — for example, a PaymentService is not a kind of PaymentMethod, it simply holds and calls one. A useful test is to ask whether every instance of the subclass could honestly answer "yes" to every promise the parent makes; if a subclass has to override a method to throw an exception or leave it empty, that's usually a sign composition would have been the better fit. In general, composition is the safer default because it produces looser coupling — the containing class depends only on the other object's public interface, not its implementation details — and that's why "favor composition over inheritance" is repeated so often in object-oriented design.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to Does the Single Responsibility Principle mean a class should only ever have one method?← Back to all Low-Level Design & Design Patterns questions