Lesson · Abstraction & Interfaces
Interfaces: a contract any class can sign
17 min readInterfaces
An interface is a type made of promises: any class, from any family, can sign it and become usable wherever that capability is expected. Default methods let the contract grow without breaking the signers.
Two families, one ability
Orders and subscriptions share no parent, yet both must be refundable. Interfaces give unrelated classes one shared type:
interface Refundable { void refund(); // a promise, no body } class Order implements Refundable { // joins the type by keeping the promise @Override public void refund() { ... } } class Subscription implements Refundable { @Override public void refund() { ... } }
Predict: why not give both classes a common parent instead? Because Java allows exactly one parent, and the two families have nothing else in common. An interface is inheritance in the other direction: not 'what you are', but what you can do.
The contract vocabulary
Four pieces, one idea: a capability that unrelated classes adopt:
| Piece | Means |
|---|---|
| interface | A type made of method signatures (and constants); no instance state, no constructors |
| implements | The class signs the contract and must provide every abstract method, or stay abstract |
| default method | A method with a body inside the interface; implementers inherit it and may override it |
| static interface method | A utility tied to the interface name, like Comparator.comparing(...); not inherited |
- Methods are public by default, in the interface and in the implementation: an implementer with weaker visibility, like a package-private
refund(), is refused by the compiler. - A class can implement many interfaces: one parent for state, any number of contracts for types.
- Interfaces extend interfaces, in any number:
interface Sized extends Comparable<Sized>, Iterable<Sized>is legal, and it adds no state ambiguity. - No instance fields: only constants (
static final). A whole interface of constants alone is the classic anti-pattern; use a final class or an enum for those.
Name the capability, not the thing. Refundable, Comparable, Iterable: if the name reads as an ability someone can have, it belongs on an interface. Nouns describing identity belong on classes.
Default methods: growing the contract safely
One day the contract needs a helper every implementer will want. Adding an abstract method breaks every existing signer; a default method does not:
- The interface declares
default String receipt() { return "refunded"; }with a real body. - Order and Subscription already exist and compile unchanged; they merely inherited one more method.
- Any implementer that wants different behaviour overrides the default like a normal method.
- The default lives once, in the interface, and evolution stops being a breaking change.
Defaults are for evolution, not for smuggling code. A capability's shared behaviour may live there, but state cannot: interfaces stay stateless, so defaults can only be written from their parameters and each other.
Contract board · who has signed
Current statement
interface Refundable
Refundable: a type with one promise and no state.
The interface declares what signers must be able to do. There is no body, no field, no constructor: the interface is a capability, not a family.
Marker interfaces: meaning with no methods
Some interfaces have no methods at all; the type itself is the message:
- `Serializable` tells the runtime an object may be serialised; there is nothing to implement because the meaning is the membership.
- `Cloneable` works the same way: marker in, cloning machinery adjusts its behaviour.
- Modern alternative: annotations carry similar metadata (
@Deprecated, frameworks' annotations), but annotations do not create a type; a marker interface still shows up in method signatures and generics.
A type can carry meaning even when it carries nothing else. if (x instanceof Serializable) is a real question with no methods involved.
The interface playbook
Designing a contract, in order:
- Name the ability from the caller's side: what does the calling code want to do? (
refund,compare,close). - Keep it minimal: one or two methods that always travel together; small interfaces compose better than large ones.
- Prefer the interface as the declared type in APIs (
void process(Refundable item)), so every present and future implementer fits. - Choose the capability over the family when both would work; it keeps classes from choosing between parents.
- When the contract must grow, add a default method with a sensible body first; save abstract additions for a major version.
A contract anyone can sign, enforced at compile time. The implementing keyword is the signature; the compile errors for a missing method are the contract's teeth.
Interfaces are capabilities: many classes, any family, one shared type
An interface lists promises and holds no state: any class can implement it, any number of interfaces at once, and every implementer becomes usable wherever the type is expected. Default methods let the contract grow without breaking existing signers, and marker interfaces prove that sometimes the type itself is the whole message.
Interview angles
What is an interface, and how does it differ from a class?+
A type made of method signatures (plus constants), with no instance state and no constructors. Classes implement it; multiple interfaces can be used at once, while class inheritance stays single.
The interface gives callers a stable type: any implementer fits wherever the interface is expected. The class keeps its own parent for state and code reuse; the interface adds a capability next to that parent, not instead of it.
interface Refundable { void refund(); } class Order implements Refundable { public void refund() { ... } } class Subscription implements Refundable { public void refund() { ... } }
Common misconception: That an interface is a class with the bodies removed. It is a different kind of type: no state, no constructors, many per class, and its job is describing capabilities.
Follow-up: Can an interface extend another interface?
What must an implementing class get right?+
Every abstract method of every implemented interface must have a public implementation (or the class must be abstract). Same name, same parameters, public visibility.
Weaker visibility is refused with the compiler's phrase attempting to assign weaker access privileges. All or nothing: leave one promise unanswered and the class either becomes abstract or fails to compile, with the error naming the missing method.
class Order implements Refundable { // void refund() { } // error: attempting to assign weaker access privileges public void refund() { } // public: the contract's visibility }
Common misconception: That package-private or protected can satisfy an interface method. Interface methods are public; implementations must be too.
Follow-up: What error appears if one method is simply missing?
Why were default methods added to Java?+
To evolve interfaces without breaking every existing implementer: a new method with a body is inherited instead of demanded, so old classes keep compiling.
The Java 8 collections upgrades leaned on this: List.forEach arrived as a default so implementations written years earlier did not break. Implementers may override the default whenever they want different behaviour.
interface Refundable { void refund(); default String receipt() { return "refunded"; } // old implementers unaffected }
Common misconception: That defaults make interfaces stateful. They may hold code, never instance state; the stateless promise is what keeps multiple inheritance of behaviour manageable.
Follow-up: What happens when two interfaces offer conflicting defaults?
What is a marker interface, and is it still useful?+
An interface with no methods whose meaning is the membership itself: Serializable and Cloneable are the classic pair. The type answers questions no method can.
Markers still appear in signatures and generics in ways annotations cannot (List<? extends Serializable> is expressible; an annotation is not a type). Annotations cover the metadata role, markers keep the type role.
interface Serializable { } // the whole contract is 'I may be serialized' if (x instanceof Serializable) { ... }
Common misconception: That markers are obsolete. Annotation-based metadata is newer, but only interfaces can play the role of a type in assignments and bounds.
Follow-up: When would you reach for an annotation instead of a marker?
When should you prefer an interface over a parent class?+
Whenever the relationship is a capability rather than an identity, especially across unrelated families: refundable, comparable, iterable, closeable.
An interface adds a type without spending the single inheritance slot, so classes keep their natural parent and still join every capability they need. This is also the honest answer when no parent would make the is-a sentence true.
class Report extends Document implements Comparable<Report>, Serializable { ... }
Common misconception: That interfaces replace inheritance. They complement it: the parent supplies state and code, interfaces supply types from every family.
Follow-up: What does an interface give up compared with a parent class?