Abstraction and Interfaces
Brew Bar now sells pastries as well as drinks, and takes payment for orders, gift cards and catering bookings. The till should not care which of those it is charging; it only needs "something with an amount due". Abstraction is the art of depending on what a thing can do while ignoring how it does it.
The rule
Abstract says what; the subclass or implementer supplies how.
An abstract class is a partial recipe. It cannot be created with new, and it may declare abstract methods, which have no body and must be filled in by subclasses:
public abstract class MenuItem {
protected final String name;
protected MenuItem(String name) {
this.name = name;
}
public abstract int priceCents(); // what, not how
public String label() { // shared, finished code
return name + " " + priceCents() + "c";
}
}
public class Pastry extends MenuItem {
public Pastry(String name) { super(name); }
@Override
public int priceCents() { return 280; }
}An interface is a pure contract of abilities. A class implements it and must provide every abstract method it lists:
public interface Payable {
int amountDueCents();
default boolean isFree() { // interfaces may carry default code
return amountDueCents() == 0;
}
}
public class Order implements Payable, Printable {
@Override
public int amountDueCents() { return totalCents(); }
// ... and Printable's methods too
}The till can now accept any Payable, whether an order, a gift card or a booking, without knowing its class.
How to choose:
- Abstract class: closely related things that share fields and code, in an "is a" family (every pastry is a menu item). A class extends only one.
- Interface: an ability that unrelated classes can share ("can be paid", "can be printed"). A class can implement many.
The shortcut
Ask "Do these share data, or just a promise?" Shared data and code → abstract class. Just a promise that several unrelated types can keep → interface. Then write the rest of your code against that abstract type, not the concrete classes.
What does the till need?
Only one fact from each thing it charges: the amount due.
Drills
Answer fast — trust the rule.
What happens with MenuItem item = new MenuItem("Muffin");?
public class GiftCard implements Payable has no amountDueCents() method. What happens?
Which declaration is legal?
Coffee beans, a gift card and a catering booking all need to be printable on a receipt. What fits best?
Remember
- Abstract says what; the subclass or implementer supplies how.
- Shared data and code → abstract class; a shared promise → interface.
- Traps:
newon an abstract type, and forgetting one method of the contract.
