TL ; DR:
A class can keep an object of another class in a field. It passes work on to that object. A Car has an Engine. This is composition.
class Car:
def __init__(self):
self._engine = Engine() # a Car has an Engine
def start(self):
self._engine.start() # the Car asks its Engine
Full lesson:
Things are often made of other things. A car has an engine. A phone has a battery.
Code works the same way. One class keeps an object of another class in a field. This is called composition.
The outer object passes some work on to its part. Car's start just calls the engine's start. This is called delegation.
Has-a or is-a?
Inheritance is for "is a". A Puppy is a Dog, so Puppy inherits from Dog. A Car is not an Engine. With class Car(Engine), every engine method would become a car method. A car has an engine, so Car keeps one in a field. It passes on only what it chooses, like start.
Why it helps
- The engine stays private. Code outside talks to the car, never to the engine.
- Each class does one job.
Engineknows how to start.Carknows its name and how to drive. - A part can be replaced. A car with a new engine is still the same car.
The leading underscore in _engine marks the field private, as in Access Modifiers.
Your task
The Engine class is ready. Car already has a name and a drive method.
Give Car a private Engine field. Create the engine in __init__.
Then write Car's start method. It calls the engine's start.
The program makes a car named "Rocket". It starts the car, then drives it.
Expected output:
Engine started
Rocket is drivingFree plan: 30 tutor messages. Premium is unlimited.
