Passing the work on
After this: Write a vehicle that asks its engine, and swap the engine while the program runs.
On this page · 5 sections · 3 checks
A taxi company moves its cars from petrol to electric, one car at a time. The car keeps its name, its owner and its history; only the engine changes. With one subclass per pair, a PetrolCar object can never become an ElectricCar. With composition, you put a new engine in the same car. This lesson writes that design and swaps the engine while the program runs.
Passing the question on
How much does a trip of 100 km cost? The vehicle does not know. It knows its name, and it knows which engine it holds. The engine knows what one kilometre costs. So the vehicle asks the engine, and multiplies the answer by the distance.
Handing a job to a part, instead of doing it yourself, is called . Work through car.trip_cost(100) for a car with a petrol engine:
- The call opens a frame for the vehicle's method, with the car in its first box and
kmholding 100. - The line inside calls the engine's cost method. A second frame opens, this time with the petrol engine in its first box. It returns 8.
- Back in the vehicle's method, 8 × 100 is 800, and that is returned.
Now put an electric engine into the same car and ask again. Step 2 now reaches the electric engine, which returns 2, and the answer is 200. The vehicle's code did not change. Its field holds a different object.
The trace below is a short version of the program: two engines with one method each, a vehicle, and the swap in the middle. The task asks you to watch which engine answers each time.
- Run the programRun it and step through. Each trip cost call opens a frame, and inside it a second frame opens for the engine's cost per km. Read the first box of that inner frame each time: which engine answers? Then watch the box car between the two calls.
class PetrolEngine: def cost_per_km(self): return 8
class ElectricEngine: def cost_per_km(self): return 2
class Vehicle: def __init__(self, engine): self.engine = engine
def trip_cost(self, km): return self.engine.cost_per_km() * km
car = Vehicle(PetrolEngine())print(car.trip_cost(100))car.engine = ElectricEngine()print(car.trip_cost(100))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The whole program
Here is the full design from lesson 2, with two of the three engines written out. Each engine has two methods, a cost per kilometre and a sound, and the vehicle has two methods that ask its engine.
class PetrolEngine: def cost_per_km(self): return 8
def sound(self): return "vroom"
class ElectricEngine: def cost_per_km(self): return 2
def sound(self): return "hum"
class Vehicle: def __init__(self, name, engine): self.name = name self.engine = engine
def start(self): return self.name + ": " + self.engine.sound()
def trip_cost(self, km): return self.engine.cost_per_km() * km
car = Vehicle("car", PetrolEngine())print(car.start())print(car.trip_cost(100))car.engine = ElectricEngine()print(car.start())print(car.trip_cost(100))truck = Vehicle("truck", ElectricEngine())print(truck.trip_cost(250))car: vroom 800 car: hum 200 500
interface Engine { int costPerKm(); String sound();}
class PetrolEngine implements Engine { public int costPerKm() { return 8; }
public String sound() { return "vroom"; }}
class ElectricEngine implements Engine { public int costPerKm() { return 2; }
public String sound() { return "hum"; }}
class Vehicle { private String name; private Engine engine;
Vehicle(String name, Engine engine) { this.name = name; this.engine = engine; }
void setEngine(Engine engine) { this.engine = engine; }
String start() { return name + ": " + engine.sound(); }
int tripCost(int km) { return engine.costPerKm() * km; }}
public class Main { public static void main(String[] args) { Vehicle car = new Vehicle("car", new PetrolEngine()); System.out.println(car.start()); System.out.println(car.tripCost(100)); car.setEngine(new ElectricEngine()); System.out.println(car.start()); System.out.println(car.tripCost(100)); Vehicle truck = new Vehicle("truck", new ElectricEngine()); System.out.println(truck.tripCost(250)); }}car: vroom 800 car: hum 200 500
Walk through it from the bottom:
caris made with aPetrolEngine.startasks the engine for its sound and printscar: vroom. The trip cost is 8 × 100:800.- One line swaps the engine. Python sets the field directly: car.engine = ElectricEngine(). Because outside code writes it, the diagram in lesson 2 marks engine with + (public) in Python.Java keeps the field private and offers a method for it: car.setEngine(new ElectricEngine()). The diagram in lesson 2 leaves this small method out, to keep the box short.
- The same car now prints
car: hum, and the same trip costs 2 × 100:200. - A
truckis made with an electric engine from the start. 2 × 250 is500.
Look at the methods of Vehicle. Neither one says "if petrol, then 8". Each passes the question to whatever engine is in the field. That is why a hybrid engine, or any engine added next year, works with this Vehicle unchanged.
Run it
Java does not run here. Step through the Java version with the trace above, or paste it into a Java tool on your computer.
Try writing a third engine, HybridEngine, with a cost of 5 and the sound purr. Then make a van with it. Vehicle needs no change.
Check yourself
The program runs car.trip_cost(100)car.tripCost(100) on a car with a petrol engine. Which object works out the cost of one kilometre?
A bus starts with an electric engine, and then its engine is swapped. What does this print?
class PetrolEngine: def cost_per_km(self): return 8
def sound(self): return "vroom"
class ElectricEngine: def cost_per_km(self): return 2
def sound(self): return "hum"
class Vehicle: def __init__(self, name, engine): self.name = name self.engine = engine
def start(self): return self.name + ": " + self.engine.sound()
def trip_cost(self, km): return self.engine.cost_per_km() * km
bus = Vehicle("bus", ElectricEngine())print(bus.trip_cost(30))bus.engine = PetrolEngine()print(bus.start())print(bus.trip_cost(30))interface Engine { int costPerKm(); String sound();}
class PetrolEngine implements Engine { public int costPerKm() { return 8; }
public String sound() { return "vroom"; }}
class ElectricEngine implements Engine { public int costPerKm() { return 2; }
public String sound() { return "hum"; }}
class Vehicle { private String name; private Engine engine;
Vehicle(String name, Engine engine) { this.name = name; this.engine = engine; }
void setEngine(Engine engine) { this.engine = engine; }
String start() { return name + ": " + engine.sound(); }
int tripCost(int km) { return engine.costPerKm() * km; }}
public class Main { public static void main(String[] args) { Vehicle bus = new Vehicle("bus", new ElectricEngine()); System.out.println(bus.tripCost(30)); bus.setEngine(new PetrolEngine()); System.out.println(bus.start()); System.out.println(bus.tripCost(30)); }}Complete the one line inside trip_costtripCost, so that the vehicle asks its engine for the cost of one kilometre and multiplies it by km. The program should print the same five lines as before.
class PetrolEngine: def cost_per_km(self): return 8
def sound(self): return "vroom"
class ElectricEngine: def cost_per_km(self): return 2
def sound(self): return "hum"
class Vehicle: def __init__(self, name, engine): self.name = name self.engine = engine
def start(self): return self.name + ": " + self.engine.sound()
def trip_cost(self, km): ________ # ← pass the question to the engine
car = Vehicle("car", PetrolEngine())print(car.start())print(car.trip_cost(100))car.engine = ElectricEngine()print(car.start())print(car.trip_cost(100))truck = Vehicle("truck", ElectricEngine())print(truck.trip_cost(250))interface Engine { int costPerKm(); String sound();}
class PetrolEngine implements Engine { public int costPerKm() { return 8; }
public String sound() { return "vroom"; }}
class ElectricEngine implements Engine { public int costPerKm() { return 2; }
public String sound() { return "hum"; }}
class Vehicle { private String name; private Engine engine;
Vehicle(String name, Engine engine) { this.name = name; this.engine = engine; }
void setEngine(Engine engine) { this.engine = engine; }
String start() { return name + ": " + engine.sound(); }
int tripCost(int km) { ________ // ← pass the question to the engine }}
public class Main { public static void main(String[] args) { Vehicle car = new Vehicle("car", new PetrolEngine()); System.out.println(car.start()); System.out.println(car.tripCost(100)); car.setEngine(new ElectricEngine()); System.out.println(car.start()); System.out.println(car.tripCost(100)); Vehicle truck = new Vehicle("truck", new ElectricEngine()); System.out.println(truck.tripCost(250)); }}Honesty notes
- Say what delegation is: a method that passes the job to a part it holds and uses the answer.
- Follow a trip cost call into the engine's cost method and back: 8 × 100 is 800 with petrol, 2 × 100 is 200 with electric.
- Swap a part while the program runs, by setting the field in Python or calling setEngine in Java, and say why the vehicle's code does not change.
- Say what lets any engine fit the field: the Engine interface in Java, and any object with the two methods in Python.