CS core subjects

Stage 2 · Lesson 6 of 8

Composition over inheritance

Object-oriented programming and design

means building an object out of other objects that it holds and hands work to. A Car has an Engine; it is not a kind of engine. With composition you can swap behaviour while the program runs.

A game character, for example, can be given a different way of moving without a new for every combination. Composition keeps classes small and loosely linked, so changes cost less. "Favour composition over inheritance" is a guideline, not a ban: inheritance still fits true "is a" relationships.

This idea sits under several you will meet next, such as Strategy and Decorator.

Common trapa class hierarchy that multiplies, such as FlyingSwimmingDuck, because every new combination of features needs its own subclass.

A question to check yourself, an AI practice session and 2 cheat sheet entries come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

  • CoursePaid
    Grokking SOLID Design Principles

    Design Gurus · Beginner · $50 one-time

    Each SOLID principle with a broken example and its fix, at a beginner-friendly pace

  • CourseFree
    Java Programming MOOC

    University of Helsinki · Beginner

    Free, exercise-heavy course whose second half is a thorough, tested introduction to OOP

Keep handy

Also worth your time

Mark this stage as not done?