13.4Composition
Covers IGNOU MCS-201 §13.4
The heading of §13.4 is “Inheritance and Compositions”, and the programme guide lists composition, but the printed unit explains only inheritance. Composition is the other main way to reuse code, and it is used in real programs more often than inheritance.
What composition is
A Car has an Engine; a University has Departments; an Order has OrderLines. The containing object delegates work to its parts by calling their methods.
| Inheritance | Composition | |
|---|---|---|
| Relationship | “is-a” | “has-a” |
| How | class Child(Parent): | self.part = Part(...) inside the class |
| Reuse | Child gets all parent members automatically | Class calls the part’s methods explicitly |
| Coupling | Tight: changes in the parent affect every child | Loose: parts can be replaced or changed independently |
| Example | SavingsAccount(Account) | Car with an Engine |
A common design rule is “prefer composition over inheritance”: use inheritance only when the child truly is a special kind of the parent and should support everything the parent does.
Key takeaways
- Composition: a class holds other objects as attributes (“has-a”).
- The outer class delegates to its parts by calling their methods.
- Composition is loosely coupled; parts can be swapped.
- Use inheritance only for true “is-a” relationships.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Design classes for “a college has departments, and each department has a head and a list of teachers”, stating which relationships are composition.
Show worked answer
Use a Teacher class (name, subject); a Department class whose constructor stores self.head (a Teacher) and self.teachers (a list of Teacher objects), with a method such as add_teacher(t); and a College class with self.departments (a list of Department objects). College has departments, department has a head and teachers: all three are “has-a” relationships, so all are composition. Inheritance would fit only a true “is-a” link, for example class Professor(Teacher).