Back to Academy
oop
Association & Composition
Composition builds complex objects by combining simpler ones through 'has-a' relationships, as opposed to inheritance's 'is-a' relationships. Like how a car is composed of an engine, transmission, and wheels — rather than inheriting from Engine — composition creates flexible, swappable designs. This avoids the fragile base class problem and deep inheritance hierarchies.
Use Cases
- •Building a notification system by composing channel, formatter, and throttler components
- •Creating game characters by mixing in abilities (fly, swim, attack) rather than a rigid class tree
- •Constructing HTTP clients by injecting auth, retry, and logging middleware
- •Assembling report generators from data source, transformer, and renderer components
Implementation
Output
Click "Run Code" to see output...