Skip to content

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.

java
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

InterfaceAbstract class
Instance fieldsNoYes
Method bodiesDefault methods onlyYes
How many can a class haveManyOne
Use it whenUnrelated classes share a capabilitySubclasses 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.

java
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.

java
List<String> names = new ArrayList<>();     // good
ArrayList<String> names = new ArrayList<>();// worse

The first can become a LinkedList by changing one line. The second cannot, because every method taking ArrayList now has to change too.