Composition builds a class by placing an instance of another class inside it. Instead of inheriting from an array or linked list, the new class owns one and forwards selected operations to it. This supports encapsulation and keeps the public interface focused. section 2.10 section 7.12
Composition is useful when a class needs to reuse an implementation while exposing a smaller, cleaner interface:
- An UnsortedArray stores a core Array instance internally and manages its own size-related state. section 2.10
- A Bag wraps a singly linked list and exposes only the operations clients need. section 7.12
- Forwarding operations keeps methods short: insertion delegates to the linked list, while traversal returns its elements. section 7.12
A class built around another class
A Bag can create a SinglyLinkedList in its constructor, send each inserted value to insert_in_front, and use the list's traversal behavior. Clients work with Bag rather than directly depending on the linked-list implementation. section 7.12
class UnsortedArray:
def __init__(self, max_size, typecode = 'l'):
self._array = Array(max_size, typecode)
self._max_size = max_size
self._size = 0
The constructor makes composition visible: UnsortedArray stores an Array instance in _array instead of deriving from Array. section 2.10










