Interfaces in Python and Java
After this: Say when each language reports a missing method, and choose between an interface and duck typing.
On this page · 6 sections · 3 checks
The checkout from lesson 3 trusts every payment to have a pay. What if someone writes a new payment class and forgets it? The two languages answer at different moments, and Python offers two ways to write the promise. This lesson compares them.
A class that forgets a method
Here is a class Broken that says it keeps the PaymentMethod promise but writes only fee. Switch between Python and Java to see each version and what it produces.
from abc import ABC, abstractmethod
class PaymentMethod(ABC): @abstractmethod def fee(self, amount): ...
@abstractmethod def pay(self, amount): ...
class Broken(PaymentMethod): def fee(self, amount): return 0
try: b = Broken() print("made it")except TypeError as e: print("TypeError:", e)TypeError: Can't instantiate abstract class Broken without an implementation for abstract method 'pay'
interface PaymentMethod { int fee(int amount); String pay(int amount);}
class Broken implements PaymentMethod { public int fee(int amount) { return 0; }}
public class Main { public static void main(String[] args) { PaymentMethod b = new Broken(); System.out.println("made it"); }}Main.java:6: error: Broken is not abstract and does not override abstract method pay(int) in PaymentMethod
The two languages report the same mistake at different moments:
- Java reads the whole file before it runs anything. This step is called .
javacsees thatBrokensaysimplements PaymentMethodbut has nopay, and stops with an error. The program never starts, somade itis never printed. - Python with the ABC accepts the class line. The check comes when the program tries to make an object:
Broken()raises aTypeErrorthat names the missing method,pay. The lineprint("made it")never runs, because the error comes first.
In both languages, a broken object never reaches the checkout. That is what the interface buys you: the mistake is reported next to the class that made it, not later, deep inside some other code.
Run it
Add a pay method to Broken that returns any text, and run it again. Now Broken() works and made it is printed.
The third way: no interface at all
In "Objects that share behaviour" you saw that Python does not need a parent class to call a method. If the object has pay, the call works. This is called .
Here is the same mistake with duck typing: Broken has no parent at all.
class Broken: def fee(self, amount): return 0
class Checkout: def __init__(self, method): self.method = method
def place_order(self, amount): return self.method.pay(amount)
c = Checkout(Broken())print("made it")try: print(c.place_order(1250))except AttributeError as e: print("AttributeError:", e)made it AttributeError: 'Broken' object has no attribute 'pay'
interface PaymentMethod { int fee(int amount); String pay(int amount);}
class Broken { public int fee(int amount) { return 0; }}
class Checkout { private PaymentMethod method;
Checkout(PaymentMethod method) { this.method = method; }
String placeOrder(int amount) { return method.pay(amount); }}
public class Main { public static void main(String[] args) { Checkout c = new Checkout(new Broken()); System.out.println("made it"); }}Main.java:26: error: incompatible types: Broken cannot be converted to PaymentMethod
In Python, nothing checks Broken in advance. The object is made, the checkout is made, and made it is printed. The mistake shows up only when the checkout calls pay, as an AttributeError. In a bigger program that call might come much later, in code far away from the class that is wrong.
Java has no duck typing. The checkout's field has the type PaymentMethod, and Broken does not say it implements it, so javac refuses to hand a Broken to the checkout.
Side by side
| Way of writing the promise | When the missing pay is reported |
|---|---|
Java interface | at compile time: the program never starts |
Python ABC with @abstractmethod | when an object of the class is made |
| Python duck typing, no parent | when pay is called on the object |
The table runs from earliest to latest. An earlier report is closer to the mistake and easier to fix.
Two more names you may meet. Python's typing.Protocol writes an interface that a separate checking tool (such as mypy) reads before the program runs; Python itself does not check it while the program runs. (A protocol marked @runtime_checkable can be tested with isinstance, but that test only looks for the method names.) And a Java interface may carry a default method, one with code inside, which every class gets unless it writes its own.
Check yourself
In Python, a class Broken is built on the PaymentMethod ABC but writes only fee, not pay. When does Python report the missing pay?
In Java, class Broken implements PaymentMethod but writes only fee, not pay. When does Java report the missing pay?
In Python, Broken has no parent at all and writes only fee. The program makes Checkout(Broken()), prints "made it", then places an order. What happens?
Honesty notes
- Say that Java reports a missing method of an interface at compile time, before the program starts.
- Say that Python's abstract base class reports it when an object of the class is made, with a TypeError.
- Say that with duck typing the mistake shows up only when the missing method is called.
- Choose: add an interface when a second kind is real, and know that in Python it is optional.