ArticleslgStudy

computer science

Composition over inheritance

Composition over inheritance is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Composition over inheritance rather than just read about it. In short: In object-oriented programming, composition over inheritance (sometimes composition with forwarding or composite reuse) is a common design pattern that tries to achieve code reuse without requiring inheritance. Instead of having two child classes inherit functionality from a common parent, composition simulates inheritance by having the children include a copy of a "pseudo-parent" class as a field, which implements…

Composition over inheritance — main illustration
Composition over inheritance — illustration

Key takeaways

  • Composition over inheritance belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Composition over inheritance to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Composition over inheritance from memory before moving on to harder problems.

Reference excerpt

In object-oriented programming, composition over inheritance (sometimes composition with forwarding or composite reuse) is a common design pattern that tries to achieve code reuse without requiring inheritance. Instead of having two child classes inherit functionality from a common parent, composition simulates inheritance by having the children include a copy of a "pseudo-parent" class as a field, which implements the functionality common to the two classes. Then, methods that would have been called on the child are instead called on the pseudo-parent, a technique called method forwarding. Composition is generally used in languages where inheritance is unavailable or has an implementation that is considered inflexible, inconvenient, or inadequate (e.g. because a language lacks multiple inheritance). However, many problems that are easily solved with inheritance are difficult to solve using only composition; as a result, inheritance and object composition typically work hand-in-hand, as discussed in the book Design Patterns (1994).

Example

Inheritance An example in C++ follows:

Then, suppose we also have these concrete classes:

class Player - which is Solid, Movable and Visible class Cloud - which is Movable and Visible, but not Solid class Building - which is Solid and Visible, but not Movable class Trap - which is Solid, but neither Visible nor Movable Note that multiple inheritance is dangerous if not implemented carefully because it can lead to the diamond problem. One solution to this is to create classes such as VisibleAndSolid, VisibleAndMovable, VisibleAndSolidAndMovable, etc. for every needed combination; however, this leads to a large amount of repetitive code. C++ uses virtual inheritance to solve the diamond problem of multiple inheritance.

Composition and interfaces The C++ examples in this section demonstrate the principle of using composition and interfaces to achieve code reuse and polymorphism. Due to the C++ language not having a dedicated keyword to declare interfaces, the following C++ example uses inheritance from a pure abstract base class. For most purposes, this is functionally equivalent to the interfaces provided in other languages, such as Java and C#. Introduce an abstract class named VisibilityDelegate, with the subclasses NotVisible and Visible, which provides a means of drawing an object:

Introduce an abstract class named UpdateDelegate, with the subclasses NotMovable and Movable, which provides a means of moving an object:

Introduce an abstract class named CollisionDelegate, with the subclasses NotSolid and Solid, which provides a means of colliding with an object:

Finally, introduce a class named GameObject with members to control its visibility (using a VisibilityDelegate), movability (using an UpdateDelegate), and solidity (using a CollisionDelegate). This class has methods which delegate to its members, e.g. update() simply calls a method on the UpdateDelegate:

Then, concrete classes would look like:

Benefits To favor composition over inheritance is a design principle that gives the design higher flexibility. It is more natural to build business-domain classes out of various components than trying to find commonality between them and creating a family tree. For example, an accelerator pedal and a steering wheel share very few common traits, yet both are vital components in a car. What they can do and how they can be used to benefit the car are easily defined. Composition also provides a more stable business domain in the long term as it is less prone to the quirks of the family members. In other words, it is better to compose what an object can do (has-a) than extend what it is (is-a). Initial design is simplified by identifying system object behaviors in separate interfaces instead of creating a hierarchical relationship to distribute behaviors among business-domain classes via inheritance. This approach more easily accommodates future requirements changes that would otherwise require a complete restructuring of business-domain classes in the inheritance model. Additionally, it avoids problems often associated with relatively minor changes to an inheritance-based model that includes several generations of classes. Composition relation is more flexible as it may be changed on runtime, while sub-typing relations are static and need recompilation in many languages. Some languages, notably Go and Rust, use type composition exclusively.

Drawbacks One common drawback of using composition instead of inheritance is that methods being provided by individual components may have to be implemented in the derived type, even if they are only forwarding methods (this is true in most programming languages, but not all; see § Avoiding drawbacks). In contrast, inheritance does not require all of the base class's methods to be re-implemented within the derived class. Rather, the derived class only needs to implement (override) the methods having different behavior than the base class methods. This can require significantly less programming effort if the base class contains many methods providing default behavior and only a few of them need to be overridden within the derived class. Thus, the pattern of "composition over inheritance" should not be interpreted as a literal mantra or law, but rather a selectively applicable suggestion to be used where appropriate. For example, in the C# code below, the variables and methods of the Employee base class are inherited by the HourlyEmployee and SalariedEmployee derived subclasses. Only the Pay() method needs to be implemented (specialized) by each derived subclass. The other methods are implemented by the base class itself, and are shared by all of its derived subclasses; they do not need to be re-implemented (overridden) or even mentioned in the subclass definitions.

Avoiding drawbacks This drawback can be avoided by using traits, mixins, (type) embedding, or protocol extensions. Some languages provide specific means to mitigate this:

… excerpt ends here. Continue reading the full article.

Illustrations

Composition over inheritance: This diagram shows how the fly and sound behavior of an animal can be designed in a flexible way by using the composition over inheritance design principle.[1]
This diagram shows how the fly and sound behavior of an animal can be designed in a flexible way by using the composition over inheritance design principle.[1]
Composition over inheritance illustration

Worked examples

Example 1 — a first encounter with Composition over inheritance

Start with the simplest possible case. Write down what Composition over inheritance claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Composition over inheritance before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Composition over inheritance ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Composition over inheritance

In research
Composition over inheritance appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Composition over inheritance in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Composition over inheritance is common in secondary-school and first-year university syllabi. It links to neighbouring topics Component-based software engineering, Programming principles, Software architecture, so understanding it makes those chapters shorter.
In everyday life
Look for Composition over inheritance outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Composition over inheritance” →

How to study Composition over inheritance in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Composition over inheritance means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Composition over inheritance out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Composition over inheritance in simple terms?

In object-oriented programming, composition over inheritance (sometimes composition with forwarding or composite reuse) is a common design pattern that tries to achieve code reuse without requiring inheritance. Instead of having two child classes inherit functionality from a common parent, composit…

Why does Composition over inheritance matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Composition over inheritance?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Composition over inheritance.

Tags

  • Component-based software engineering
  • Programming principles
  • Software architecture

Keep exploring