Lesson 11 of 23
In progress
Interfaces
Define a contract, implement it across unrelated classes, and use default methods without turning the interface into a base class.
An interface names a capability. It says what a class can do without saying how, which lets unrelated classes be used interchangeably by the code that needs the capability.
What you will learn
- Declare and implement an interface.
- Use default and static methods appropriately.
- Design small interfaces that compose.
The contract
public interface Notifier {
void send(String to, String message);
}
public class EmailNotifier implements Notifier {
@Override
public void send(String to, String message) {
System.out.println("email to " + to + ": " + message);
}
}
public class SmsNotifier implements Notifier {
@Override
public void send(String to, String message) {
System.out.println("sms to " + to + ": " + message);
}
}
Implementing methods must be public, because the interface’s methods are public by default. Forgetting public produces a compile error about weaker access, which is at least explicit.
A class can implement several interfaces, which is how Java provides multiple types without multiple inheritance:
class LoggingNotifier implements Notifier, AutoCloseable {
public void send(String to, String message) { }
public void close() { }
}
Using the interface as the type
static void notifyAll(java.util.List<Notifier> notifiers, String to, String message) {
for (Notifier notifier : notifiers) {
notifier.send(to, message);
}
}
The method does not know or care which implementations it receives. That is the payoff: a new channel is added by implementing Notifier and passing it in, with no change to the caller.
This is dependency inversion in miniature. The high-level code depends on an abstraction, and the concrete classes depend on the same abstraction.
Default methods
An interface can provide a method body:
public interface Notifier {
void send(String to, String message);
default void sendAll(java.util.List<String> recipients, String message) {
for (String recipient : recipients) {
send(recipient, message);
}
}
}
sendAll is inherited by every implementation and calls the abstract method, so each class gets the loop for free. Default methods were added so interfaces could grow without breaking existing implementations.
They have a cost: an interface with many default methods becomes a base class in disguise, carrying behaviour and sometimes state through fields it cannot have. Keep defaults small and derived from the abstract methods.
If two interfaces provide the same default method, the class must override it and can call either with Interface.super.method():
@Override
public void sendAll(java.util.List<String> recipients, String message) {
Notifier.super.sendAll(recipients, message);
}
Static methods on interfaces
public interface Notifier {
void send(String to, String message);
static Notifier noop() {
return (to, message) -> { };
}
}
A static method on an interface is a factory or helper that belongs with the contract. Notifier.noop() is a null-object implementation, useful in tests and defaults, and it reads better than a separate utility class.
Small interfaces
interface Reader { String read(); }
interface Writer { void write(String text); }
Two small interfaces can be combined:
interface ReadWriter extends Reader, Writer { }
A class that only reads implements Reader; a test double does the same without pretending to write. Splitting a five-method interface into two focused ones is usually an improvement, because callers depend only on what they use.
The counter-pressure is proliferation: an interface per method makes the code hard to navigate. Split where the methods are used by different callers, not for symmetry.
Marker interfaces and annotations
An interface with no methods marks a capability: Serializable, Cloneable. Modern Java often uses annotations instead, because they can carry data and do not affect the type hierarchy. Use a marker interface when the type itself must be expressible in a signature.
Interfaces versus abstract classes
| Need | Choose |
|---|---|
| A contract several unrelated classes can satisfy | Interface |
| Shared state or a partial implementation with a constructor | Abstract class |
| Both | Abstract class implementing the interface |
An abstract class can have fields and constructors, so it can hold state and enforce invariants. An interface cannot, which is why it is the better choice for a pure contract.
The usual design keeps the interface public and small, with an abstract class or a default method providing convenience where it earns its place.
Naming
Name an interface after the capability: Comparable, Runnable, Notifier, Exportable. The -able suffix is a convention for capabilities and reads well in a type position.
Avoid INotifier or NotifierInterface. The type name should not encode that it is an interface; the code that uses it does not care.
Adding a method to a widely implemented interface without a default, which breaks every implementation and every test double at once. Add a default that delegates, or introduce a new interface.
Define a Discount interface with long apply(long paise), implement a percentage discount and a flat discount, and write a method that applies a list of discounts in order.
Show solution
import java.util.List; public class Pricing { interface Discount { long apply(long paise); } record Percent(int value) implements Discount { public long apply(long paise) { return paise - (paise * value / 100); } } record Flat(long paise) implements Discount { public long apply(long amount) { return Math.max(0, amount - paise); } } static long finalPrice(long paise, List<Discount> discounts) { long current = paise; for (Discount discount : discounts) { current = discount.apply(current); } return current; } public static void main(String[] args) { System.out.println(finalPrice(100_000L, List.of(new Percent(10), new Flat(5_000L)))); } } Each discount is a small class with one method, and the loop applies them in the order given. Flat clamps at zero so a large discount cannot make the price negative, which is the kind of rule each implementation should own.
Recap
- An interface is a public contract; implementations are interchangeable wherever the interface is expected.
- Default methods let an interface grow, but too many turn it into a base class.
- Prefer several small interfaces to one large one, and keep the type name free of
Iprefixes.
Next, abstract classes: partial implementations for a family of related types.
Can an interface extend a class?
Are interface methods public?
Progress is saved in this browser only. No account, no email.