Skip to main content
Contents Index
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 8.3 Composition vs. Inheritance: Choosing Wisely
There are two primary ways to reuse functionality between classes:
composition and
inheritance .
In real-world design scenarios, the choice between these approaches often involves nuanced trade-offs rather than clear-cut decisions:
Inheritance ("is-a" relationship):
Composition ("has-a" relationship):
A good starting question is: "Is this class genuinely a specialized version of another, or does it simply contain or use another object?" However, real designs often involve judgment calls where the lines blur. Many experienced developers adopt the "favor composition over inheritance" guideline while recognizing that inheritance is sometimes the clearer approach.
It’s also common to use both approaches together. For example, you might have a class hierarchy for game entities (inheritance) where each entity contains component objects like weapons or abilities (composition).
Checkpoint 8.3.1 .
Which of the following best describes the two primary ways to reuse functionality between classes?
Using composition to model "is-a" relationships and inheritance for "has-a" relationships.
Using inheritance to derive behavior from a parent class and composition to include functionality from other classes.
Using inheritance to derive behavior from a parent class and composition to include functionality from other classes.
Copying and pasting code between classes and using interfaces.
Writing separate methods for each class to avoid dependencies.
Checkpoint 8.3.2 .
In which scenario is composition a better choice than inheritance?
When a class needs to share behavior across multiple unrelated classes.
When a subclass needs to override most of the superclass methods.
When a class represents a "has-a" relationship rather than an "is-a" relationship.
You have attempted
of
activities on this page.