Composition is when a class contains objects of other classes as fields. Ideally, you build complex objects by assembling simpler, reusable parts.
1. What is Composition?
Composition models a "Has-A" relationship. A Car HAS-A Engine. A Person HAS-A Address. This is different from Inheritance ("Is-A").
Concept
1// The Part2class Engine {3 void start() => print('Engine running');4}5 6// The Whole7class Car {8 String model;9 Engine engine; // Composition: Car HAS-A Engine10 11 Car(this.model, this.engine);12 13 void drive() {14 engine.start(); // Delegating work to the component15 print('$model is moving');16 }17}HintThe Car does not need to know HOW the engine works, it just uses it.
2. Real World Example: Person & Address
Let's break down a complex data model into smaller pieces.
Structuring Data
1// 1. Create the smaller, independent class2class Address {3 String street;4 String city;5 String zip;6 7 Address(this.street, this.city, this.zip);8 9 String fullAddress() => '$street, $city $zip';10}11 12// 2. Create the main class composed of the smaller one13class Person {14 String name;15 Address address; // Person HAS-A Address16 17 Person(this.name, this.address);18 19 void introduce() {20 print('Hi, I am $name.'); 21 print('I live at ${address.fullAddress()}');22 }23}24 25void main() {26 var home = Address('123 Main St', 'Algiers', '16000');27 var ali = Person('Ali', home);28 29 ali.introduce();30}HintThis separates concerns: The Person class handles person things, and Address handles address formatting.
3. Composition vs Inheritance
A common rule in programming is "Favor Composition over Inheritance". It makes code more flexible and easier to test.
Flexibility
1// Easy to swap parts with Composition2var electricEngine = Engine();3var car = Car('Tesla', electricEngine);4 5// Harder with Inheritance6// class ElectricCar extends Car { ... }7// You end up with deep hierarchies like SportElectricCar, LuxuryGasCar, etc.HintInheritance locks you into a rigid hierarchy. Composition lets you mix and match parts.
Loot collected
Key takeaways- Composition = "Has-A" relationship (Person has an Address).
- Inheritance = "Is-A" relationship (Dog is an Animal).
- Composition allows you to reuse code by containing instances of other classes.
- It helps keep your classes small and focused on a single responsibility.
Side quests
Practice exercises
Exercise 1: Computer Builder
Create individual classes CPU, RAM, and HardDrive, then create a Computer class that contains them.
Reveal solutionHide solution
1class CPU {} class RAM {} class Computer { CPU cpu; RAM ram; Computer(this.cpu, this.ram); }Exercise 2: User Profile
Create a Profile class with bio and avatarUrl, then add it to a User class.
Reveal solutionHide solution
1class User { Profile profile; User(this.profile); }