7 · 32 · 5 min
Abstraction: depending on what, not how
Encapsulation hides the inside of one class. Abstraction hides which class it is at all.
interface PaymentMethod {
boolean pay(double amount);
}Code holding a PaymentMethod can call pay. It cannot know whether that is a card, a wallet or a bank transfer, and it does not need to.
Interface or abstract class
| Interface | Abstract class | |
|---|---|---|
| Instance fields | No | Yes |
| Method bodies | Default methods only | Yes |
| How many can a class have | Many | One |
| Use it when | Unrelated classes share a capability | Subclasses share state and code |
The question that decides it is state. If the things share data, an abstract class can hold it. If they only share a capability, an interface is right, and a class can implement several.
abstract class Shape {
protected String name; // shared state
abstract double area(); // each does its own
public String describe() { // shared code
return name + " has area " + area();
}
}The rule that follows
Depend on the interface, not the implementation.
List<String> names = new ArrayList<>(); // good
ArrayList<String> names = new ArrayList<>();// worseThe first can become a LinkedList by changing one line. The second cannot, because every method taking ArrayList now has to change too.