Dataslope logoDataslope

Interfaces

Pure contracts — describing what an object can do without saying anything about what it is

An interface in Java is a contract. It says "any class that implements me promises to provide these methods." It tells you nothing about state, nothing about inheritance, and nothing about implementation. It is the most flexible building block in OOP.

If a class is "what an object is," an interface is "what an object can do." A Cat, a Doorbell, and a MotionSensor are completely unrelated kinds of things — but all three could implement an interface called Noisy because all three can make a sound.

A first interface

The dashed line <|.. in UML means "implements an interface" (as opposed to <|-- for "extends a class"). In Java, the keywords are interface and implements.

Code Block
Java 8 (Update 492)

Notice the loop in Main. It does not know — and does not care — which class each element is. It only knows that each one is a Noisy, and therefore can be sent the message sound().

That ability to treat different classes uniformly through a shared interface is the secret weapon of OOP. It's what lets your code be open to new collaborators without being rewritten.

Interfaces vs. abstract classes

Both interfaces and abstract classes let you write code against a shape. They differ in a few crucial ways.

InterfaceAbstract class
Extends/implementsA class can implements many interfacesA class can extends only one class
StateNo instance fields (public static final constants only)Can have instance fields
ConstructorNoneYes, called via super(...)
Best forA capability or role that may cut across class hierarchiesA partial implementation with shared state

The single most important sentence on this page: a Java class can implement as many interfaces as it wants, but extend at most one class. Interfaces are how Java avoids the worst pitfalls of multiple inheritance while still letting an object play several roles.

Robot is at once a Movable, a Drawable, and a Loggable. Any function that needs any one of those capabilities can accept a Robot.

Programming to an interface, not an implementation

Recall the GoF principle:

Program to an interface, not an implementation.

The practical form: when you declare a variable, parameter, or return type, prefer the interface type over a specific class.

Code Block
Java 8 (Update 492)

report(List<String>) works for ArrayList, LinkedList, an immutable list, or any future List implementation that doesn't exist yet. The method signature has no opinion. That is what "programming to an interface" buys you.

Default methods: a small modern wrinkle

Since Java 8, an interface may include default methods — methods with a body that implementers inherit unless they override it. Default methods are useful when you want to add a method to an interface without breaking every existing implementer.

Code Block
Java 8 (Update 492)

Default methods do not turn an interface into a class. There is still no state. But they let interfaces grow more gracefully over time.

A small modeling example: payment processors

Imagine a checkout system that supports several payment processors (Stripe, PayPal, a test fake). Each is a totally different implementation, but the checkout doesn't care — it just wants something that can charge(amount).

Code Block
Java 8 (Update 492)

Checkout programs against the interface PaymentProcessor. Adding a new payment provider tomorrow means writing one new class — no changes to Checkout. That is the design payoff of interfaces.

Practice

Challenge
Java 8 (Update 492)
Sortable, in three different ways

Build a tiny example of programming to an interface.

  • Comparable2<T> is an interface declaring int compareWith(T other). Negative means "I am less than other", 0 means equal, positive means "I am greater".
  • Length is a class wrapping a double value. Implement Comparable2<Length> by comparing values numerically.
  • Name is a class wrapping a String value. Implement Comparable2<Name> by comparing strings alphabetically (use String.compareTo).
  • The provided Main runs a tiny scenario and is expected to print exactly:
length: -1
length: 0
length: 1
name: -1
name: 0
name: 1

(The expected values come from Integer.signum of the comparison results.)

Test your understanding

QuestionSelect one

In Java, a single class may...

Implement at most one interface and extend at most one class

Implement many classes and extend many interfaces

Implement many interfaces but extend at most one class

Implement many interfaces and extend many classes

QuestionSelect one

What does "program to an interface, not an implementation" mean in practice?

Always write interface for every class

Never use concrete classes

When declaring variables, parameters, and return types, prefer the more general interface type so callers aren't locked to a specific implementation

Use only abstract classes

QuestionSelect one

What is the main difference between an interface and an abstract class in Java?

An interface can have a constructor; an abstract class cannot

An interface has no instance state; an abstract class may have fields, a constructor, and concrete methods

An interface can extend many other interfaces; an abstract class cannot extend anything

They are exactly the same since Java 8 added default methods

On this page