Skip to content
Veltoryx Technologies
ProLesson 2.1Beginner9 min readUpdated 31 October 2026

Composition Over Inheritance

Learn why building classes from small, swappable parts usually beats building them from deep family trees, with a clear test for when inheritance is still the right tool.

Think about two ways to build a toy. The first way is to carve it from one solid block of wood. If you later want to change one arm, you must carve a whole new toy. The second way is to snap it together from LEGO bricks. If you want a different arm, you pull one brick off and snap another on.

Inheritance is like carving from one block: a child class is built on top of a parent class and carries everything the parent has. Composition is like LEGO: an object is built by holding other small objects, each doing one job, and you can swap them. Both are useful, but in design work composition is the safer default. This lesson explains why, and it also gives you a clear test for the cases where inheritance is still the right choice.

01What inheritance gives you, and what it costs

When a class says extends, it gets two things for free. It reuses the parent's code, and it can be used wherever the parent is expected. That is why inheritance feels so attractive: write once, reuse everywhere.

But there is a price, and you pay it later:

  • The child is tied tightly to the parent. If the parent changes, every child may break, even if nobody touched the child's code. This is called the fragile base class problem.
  • A child inherits everything, including things it does not want. You cannot choose to inherit only the good parts.
  • A Java class can extend only one parent. If you need two different "kinds of" behaviour, you cannot get both.
  • The relationship is fixed forever. A Car that extends Vehicle stays a Vehicle for its whole life. You cannot change it while the program runs.
  • Hierarchies grow without limit. Each new variation tends to add a new class, and soon nobody can see the whole tree.

Let us see these problems in a small, concrete story.

Loading the rest of the lesson…