Interfaces

An interface is a contract: the operations a type promises, with no say in how they are done. Code that depends on the contract can work with any implementation.

Overview

An interface lists operations and their signatures, and nothing else. A class that implements the interface promises to provide every one of them. Code that needs those operations depends on the interface, not on any particular class, so any implementation can be handed in: a real payment gateway in production, a fake in tests, a new provider next year.

This is the most useful tool in low-level design. Almost every pattern (Strategy, Observer, Repository, Adapter) is an interface plus a rule about who implements it. Interviewers listen for whether you introduce an interface at the right seams: where behavior varies, where a dependency is slow or external, and where two teams need to work in parallel.

A contract with no body

A checkout that takes payments shows the idea. One interface sits at the top, and every way to pay is a class that promises its methods.

In Java the rules are strict and worth knowing exactly. A method declared in an interface without a body is implicitly public abstract. A field declared in an interface is implicitly public static final, so it is a constant, not state. A class may implement any number of interfaces, and an interface may extend several others. Since Java 8 an interface may also carry default methods (with a body, inherited by implementers) and static methods; since Java 9, private helper methods for those bodies.

Each of those rules has a reason in design.

  • Abstract methods: allowed, and implicitly public. They are the contract itself.
  • Constants: allowed, and implicitly public static final. They are shared names, never state.
  • Instance fields: not allowed. An interface has no state to protect.
  • Default methods: allowed since Java 8. They let you evolve a published contract without breaking implementers.
  • Static methods: allowed since Java 8. They hold factories and helpers tied to the contract.
  • Constructors: not allowed. You never instantiate a contract.

Interview questions

  • When would you choose an interface over an abstract class?
  • Why should code depend on an interface rather than a concrete class?
  • How do interfaces give you multiple inheritance without the diamond problem?
  • What is duck typing, and when do you want an explicit interface instead?
  • How do you keep an interface from growing into a fat one?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio