Command Palette

Search for a command to run...

Back to the lesson: Topic 5.12 — Composition over Inheritance
Core Java · Example 1 of 4

Composition: a counting set that wraps any Set

Composition means building a class by holding other objects in fields and delegating work to them (has-a), instead of inheriting from them (is-a). It avoids the fragile base class problem and lets behaviour change at run time, so prefer it unless the relationship is a true, stable is-a.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a Car that has an Engine interface field with PetrolEngine and ElectricEngine implementations. car.start() delegates to the engine. Swap the engine at run time.

02

Write a decorator UpperCaseWriter around an interface Writer { String write(String s); } and stack two decorators: one upper-cases, one adds !.

03

Rewrite class Stack2 extends ArrayList<Integer> as a class that composes an ArrayDeque<Integer> and exposes only push, pop, peek and isEmpty.

Explain it without notes

01

What is the difference between composition and inheritance? Give an example of each.

02

Explain the fragile base class problem using the counting HashSet example.

03

How does composition enable changing behaviour at run time?

04

When is inheritance the right choice?

Composition: a counting set that wraps any Set
Sign in to run this example in your browser.

Expected output

attempts = 3, size = 3
attempts = 4, size = 3
[apple, fig, pear] attempts = 3