Interfaces & complete decoupling
◈ 7 cardsA pure contract: no implementation, no state — and a class may implement many.
The pure contract
An interface is a contract with (classically) no implementation at all — it says what methods a type provides, never how. Where an abstract class can be "partly built," an interface is "nothing but the API." This gives complete decoupling: code written against an interface neither knows nor cares which concrete class actually shows up at run time.
Classic rules (the ones an exam tests):
- Interface methods are implicitly
publicandabstract— you write the signature, no body. - A class uses
implements(notextends) and must provide a body for every method. - A field declared in an interface is implicitly
public static final— a constant, not instance state. - A class may implement many interfaces (
implements A, B, C) — Java's controlled form of "multiple inheritance," because interfaces carry no state to collide.
Worked example — the project's Fixable
The Greenhouse system needs anything that can recover from a fault to expose two operations — attempt a fix and record what happened. That is a contract, so it is an interface:
public interface Fixable {
void fix();
void log();
}
Two unrelated classes can both satisfy it without sharing a base class:
class FixWindow implements Fixable {
public void fix() { /* close & reseal the window */ }
public void log() { /* append to fix.log */ }
}
class FixPower implements Fixable {
public void fix() { /* switch to backup power */ }
public void log() { /* append to fix.log */ }
}
Now recovery code can hold Fixable f and call f.fix(); f.log(); against either class — it is decoupled from the concrete type. A class can also be a Fixable and something else at once:
class Restart extends Event implements Fixable, Runnable {
public void action() { /* reschedule events */ }
public void fix() { /* ... */ }
public void log() { /* ... */ }
public void run() { /* ... */ }
}
It extends exactly one class but implements as many interfaces as it needs — each adds a capability without adding state.
A note on default methods (Java 8+)
Modern Java lets an interface supply a default method with a body so implementers can inherit it. The AU exam is anchored to Thinking in Java 4e (pre-Java-8), so treat the classic "no bodies" rule as the exam answer, and default methods as real-world context.