Interfaces, and when to stop
After this: Say what a Java interface promises, what Python needs instead, and when a field is better than a parent.
On this page · 6 sections · 3 checks
Look back at the loop in the last lesson. In Python, would it still work if Circle and Rect were not built on Shape at all? Yes. The loop only asks each object for area(); it never looks at the parent. Java is different: the box Shape s must have a type, and that type must promise area. This lesson shows what each language needs, and then when not to build one class on another at all.
Python: if it has the method, call it
In Python, any object with an area method can go in the list. Here Circle and Square share no parent, and the loop works.
import math
class Circle: def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
class Square: def __init__(self, side): self.side = side
def area(self): return self.side * self.side
shapes = [Circle(1), Square(1.5)]for s in shapes: print(round(s.area(), 2))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
That is how Python thinks about sharing: it does not ask what class an object is, only whether it has the method being called. The cost is that nothing checks the promise. If a class forgets area, the loop fails when it reaches that object, not before.
Java: an interface
Java wants the promise written down. An is a list of methods with no code: interface Shape { double area(); }. A class says implements Shape and must then provide area, or Java refuses the file. A box of type Shape can hold any object whose class implements it.
import math
class Circle: def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
class Square: def __init__(self, side): self.side = side
def area(self): return self.side * self.side
shapes = [Circle(1), Square(1.5)]for s in shapes: print(round(s.area(), 2))3.14 2.25
import java.util.ArrayList;import java.util.List;
interface Shape { double area();}
class Circle implements Shape { int r;
Circle(int r) { this.r = r; }
@Override public double area() { return Math.PI * r * r; }}
class Square implements Shape { double side;
Square(double side) { this.side = side; }
@Override public double area() { return side * side; }}
public class Main { public static void main(String[] args) { ArrayList<Shape> shapes = new ArrayList<>(List.of(new Circle(1), new Square(1.5))); for (Shape s : shapes) { System.out.println(String.format("%.2f", s.area())); } }}3.14 2.25
When not to build on another class
Inheritance says "is a": a circle is a shape. Many links between things are not like that. A car is not an engine; a car has an engine. Giving a class a field that holds another object is called : Car has an Engine field, and car.start() works by calling self.engine.start()engine.start().
class Engine: def __init__(self, power): self.power = power
def start(self): return "vroom " + str(self.power)
class Car: def __init__(self, engine): self.engine = engine
def start(self): return self.engine.start()
car = Car(Engine(90))print(car.start())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
Watch the car box: Car(engine=Engine(power=90)), one object holding another. Two frames named start open, one for the car and, inside it, one for the engine.
class Engine: def __init__(self, power): self.power = power
def start(self): return "vroom " + str(self.power)
class Car: def __init__(self, engine): self.engine = engine
def start(self): return self.engine.start()
car = Car(Engine(90))print(car.start())vroom 90
class Engine { int power;
Engine(int power) { this.power = power; }
String start() { return "vroom " + power; }}
class Car { Engine engine;
Car(Engine engine) { this.engine = engine; }
String start() { return engine.start(); }}
public class Main { public static void main(String[] args) { Car car = new Car(new Engine(90)); System.out.println(car.start()); }}vroom 90
The rule for choosing: say the sentence out loud. "A circle is a shape": inheritance. "A car has an engine": composition. When both sound fine, choose composition. It is simpler to change later, because the car can be given a different engine without changing what a car is.
Two more warnings. A chain of classes several levels deep (a Thing, then a Vehicle, then a Car, then a SportsCar) makes every method hard to find; two levels, as in this tutorial, is plenty for a long time. And do not build on a class only to borrow one method; a field holding one of its objects does the same job without the "is a" claim.
Run it
Give Engine a stop method that returns "silence", give Car a stop that calls it, and print car.stop().
Check yourself
Three pairs of things. Which pair is a case for inheritance, where one class is built on the other?
A list holds a Circle and a Square, two classes with no shared parent, and a loop calls s.area() on each. What does the loop need from each class?interface Shape { double area(); } is declared, and class Square implements Shape. What must Square do for the file to be accepted?
A Bike has a Bell. What does this print?
class Bell: def ring(self): return "ding"
class Bike: def __init__(self): self.bell = Bell()
def ring(self): return self.bell.ring() + "!"
print(Bike().ring())class Bell { String ring() { return "ding"; }}
class Bike { Bell bell;
Bike() { this.bell = new Bell(); }
String ring() { return bell.ring() + "!"; }}
public class Main { public static void main(String[] args) { System.out.println(new Bike().ring()); }}Honesty notes
- Say what Python needs for a loop over mixed objects: each object has the method, and nothing more.
- Say what a Java interface is: a list of method promises with no code, which a class fulfils with implements.
- Tell "is a" from "has a", and choose a field (composition) over a parent class when the link is "has a".
- Say why a chain of classes several levels deep is hard to read, and keep a family of classes to two levels.