Skip to the guide

Abstraction and interfaces

BeginnerConcept6 pages

Abstraction means a caller uses a class through what it does, without knowing how it does it. An interface writes that "what" down as a type. Interviewers want to hear what your interface promises, how your language says it, and when an abstract class is the better tool.

Interpreters at an international meeting

Think of the chair of a meeting where delegates from several countries give reports. The chair speaks only English, so the meeting has one rule: every report reaches the chair in English. Each delegate brings an interpreter who turns her words into English. The chair never learns French or Japanese, and a new delegate can join with her own interpreter without the chair changing anything.

The interpreters work from a shared booth, where the headset, the microphone and a notepad are already set up. Each interpreter brings only her language. One delegate gives no speech of her own. She sums up two other delegates' reports, in English, and never needs the booth.

In code, the chair is a Thermostat, which turns the heating on while the room is below its target. The rule "in English" is the interface TemperatureSensor, whose one method, celsius(), promises degrees Celsius. Each delegate with her interpreter is a sensor class: the device's own unit is her language, and the conversion inside celsius() is the interpreting. The booth is an abstract class, ReadingSensor, which keeps each device's last reading. The delegate who sums up is AverageSensor, which averages two other sensors and keeps no reading at all. Hiding how each sensor works behind one promise is abstraction.