Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 201 ยท Object-Oriented Programming

Interfaces

Learn Java interfaces - implementing one or many, default, static and private methods, constants, marker interfaces, and when to pick an interface over an abstract class.

An interface is a named list of capabilities: "anything of this type can do these things". It says nothing about what the object is or how it stores its data. A Comparable can be compared, a Runnable can be run, an AutoCloseable can be closed. A class signs the contract with implements and then must supply every promised method.

Interfaces are the backbone of well-designed Java. The collections framework is built on List, Set and Map; lambdas work because of functional interfaces; every framework you'll use later (Spring, JDBC, servlets) hands you interfaces and lets you plug in your own classes. This lesson covers declaring and implementing interfaces, implementing several at once, the default, static and private methods added in Java 8 and 9, constants, marker interfaces, and how to choose between an interface and an abstract class.

Declaring and implementing an interface

An interface declares methods without bodies. They are automatically public and abstract, so you don't write those words:

Java
interface Shippable {
    double weightKg();          // implicitly public abstract
    String label();
}

A class that implements the interface must provide a public body for each method. Otherwise it must be declared abstract.

Java Unrelated classes sharing one interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Book and Laptop have nothing in common: no shared parent class, no shared fields. Yet both can travel in a List<Shippable>, and the loop treats them the same way. That's the main power of interfaces: they connect classes by what they can do, across unrelated hierarchies.

Notice that both implementations say public. Interface methods are public, and an override can't reduce access, so leaving public off is a compile error:

Java
class Box implements Shippable {
    double weightKg() { return 1; }     // package-private: too narrow
    public String label() { return "Box"; }
}
// error: weightKg() in Box cannot implement weightKg() in Shippable
//   attempting to assign weaker access privileges; was public

Like abstract classes, interfaces can't be instantiated (new Shippable() fails), but they work as variable, parameter, return and generic types. Program to interfaces: declare List<String> names = new ArrayList<>(); rather than ArrayList<String> names, so you can switch implementations later without touching the rest of the code.

Implementing several interfaces

A class can extend only one class, but it can implement any number of interfaces, separated by commas. Interfaces can also extend other interfaces, and an interface may extend several at once:

Java One class, several capabilities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A Note is a Document, a Printable, a Searchable and an Archivable at the same time. Each piece of code sees only the part it needs: printAll knows nothing about searching or archiving. Small, focused interfaces like these are easier to implement and to test than one giant interface; that idea is the "I" in SOLID (interface segregation).

If you also extend a class, extends comes first: class Note extends Item implements Document, Archivable.

Constants in interfaces

Fields declared in an interface are automatically public static final, so they are constants:

Java
interface Limits {
    int MAX_UPLOAD_MB = 25;     // public static final
}

You'll see this in older code. Avoid using an interface only to hold constants (the "constant interface" anti-pattern): implementing it just to use short names leaks those constants into your class's public API. Put constants in the class or enum that owns the concept, or in a final utility class, and use import static if you want short names.

Default methods

Before Java 8, adding a method to a published interface broke every class that implemented it. Default methods solve that: an interface can provide a method with a body, marked default. Implementing classes inherit it and may override it.

This is how List.sort, Collection.removeIf, Map.getOrDefault and Iterable.forEach were added to interfaces that millions of classes already implemented.

Java Default methods and resolving a conflict

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three things to notice:

  • Greeter has one abstract method, so it's a functional interface and a lambda can implement it (name -> "Hello, " + name). The lambda gets greetAll for free. You'll use this constantly in Lambda Expressions and Functional Interfaces.
  • Inside an override, InterfaceName.super.method() calls the interface's default version, much like super.method() calls a superclass method.
  • Phone inherits two defaults with the same signature. Java won't guess, so without an override the class fails with types Camera and Radio are incompatible; class Phone inherits unrelated defaults for status() from types Camera and Radio. You must override and decide, often by calling one or both X.super.status().

When defaults and classes meet, the rules are simple: a method from a class always wins over an interface default, and a more specific interface (one that extends another) wins over the one it extends.

Default methods exist to evolve interfaces, not to sneak state into them. An interface still has no instance fields, so a default method can only work through the interface's other methods. If you need shared fields, use an abstract class.

Static and private methods

Interfaces can also contain:

  • static methods (Java 8): helpers and factories that belong to the interface itself, such as List.of(...), Comparator.naturalOrder() and Map.entry(k, v). Call them through the interface name. Unlike static methods in classes, they are not inherited by implementing classes.
  • private methods (Java 9): helpers shared by several default or static methods, hidden from implementers and callers.
Java Static factories and private helpers in an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Callers write Temperature.celsius(37) and never see a concrete class name; the implementations are lambdas. Hiding implementations behind static factory methods lets you change them later without breaking callers, which is exactly what List.of does: it returns different hidden classes depending on how many elements you pass.

A complete list of interface members

Member Modifiers you write Implicit modifiers Since
Abstract method none public abstract 1.0
Constant none public static final 1.0
Default method default public 8
Static method static public (or private static) 8
Private method private (optionally static) none 9
Nested type (class, interface, enum, record) none public static 1.1+

Interfaces can't have constructors, instance fields, instance initializer blocks or protected members.

Marker interfaces

A marker interface has no methods at all. Implementing it tags a class with a property that other code checks with instanceof or that the JVM treats specially:

  • java.io.Serializable allows objects to be written by Java serialization (Serialization).
  • java.lang.Cloneable tells Object.clone() that copying is allowed (Copying Objects).
  • java.util.RandomAccess says a list has fast index access, so algorithms can choose indexed loops.
Java Checking a marker interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

For new code, annotations are often a better way to attach metadata. A marker interface still has one advantage: it's a real type, so the compiler can check it in method signatures.

Interface or abstract class?

Interface Abstract class
How many can a class use? Any number (implements A, B, C) One (extends Base)
Instance fields No (constants only) Yes
Constructors No Yes
Method bodies default, static, private methods Any methods
Member access Public (plus private helpers) Any access level
Typical meaning "can do" (capability, role) "is a kind of" (shared base)
Works with lambdas Yes, if it has one abstract method No

The practical guideline: start with an interface. It's the most flexible contract, and any class, even one that already extends something else, can implement it. Add an abstract class when several implementations share real state or code, and have it implement the interface. The JDK does this repeatedly: List (interface) with AbstractList (skeleton), Map with AbstractMap.

When you want to control exactly which classes may implement an interface, Java 17 adds sealed interfaces; see Sealed Classes and Interfaces.

Nested interfaces

An interface doesn't have to live in its own file. You can declare it inside a class or inside another interface, which is a good fit when the interface only makes sense next to its outer type. The JDK is full of them: Map.Entry is the key-value pair a Map hands you, Thread.UncaughtExceptionHandler is the callback a Thread calls when it dies, and Character.UnicodeScript sits inside Character.

Java
public class Downloader {
    public interface Progress {           // full name: Downloader.Progress
        void update(int percent);
    }

    public void start(Progress listener) { /* ... */ }
}

The rules are short:

  • A nested interface is always static. Writing static is allowed but redundant. An interface has no instance fields, so it can never be tied to an object of the outer class the way an inner class is. You never need an outer instance to use it.
  • Outside code uses the qualified name, Downloader.Progress, or imports it: import com.example.Downloader.Progress;.
  • Inside a class, a nested interface can have any access level. Make it private when only the class itself uses the abstraction, or public when callers must implement it.
  • Inside another interface, every member type is implicitly public static, just like the constants and methods there (see the member table above).

Nested interfaces are most common for callbacks and listeners that belong to one class, and for small "parts" of a bigger contract, like Map.Entry. Grouping them this way keeps the package namespace clean and makes the relationship obvious from the name.

Java A listener interface nested in its class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Interfaces can nest types too. A common modern pattern puts an interface's implementations right inside it, usually records, so the whole family reads as one unit. Combined with sealed (see Sealed Classes and Interfaces), the compiler knows every implementation, and a pattern-matching switch needs no default:

Java Records nested inside a sealed interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Shape.Circle, Shape.Square and Shape.Visitor are all public static members of Shape. Because the records are declared in the same compilation unit as the sealed interface, Java infers the permits list, so you don't have to write it.

Don't nest just to nest. If several unrelated classes implement an interface, or it is a central type of your design, give it its own top-level file. Nest it when the outer type is the reason it exists.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside interface Store { int LIMIT = 10; void save(String s); }, what are the implicit modifiers?

    Interface fields are always constants (public static final), and interface methods without a body are public abstract.
  2. 2. A class implements Store and writes void save(String s) { } without public. What happens?

    An implementation can't reduce the access of an interface method, which is public. Add the public modifier.
  3. 3. Interfaces A and B both declare default String id(). What must class C implements A, B do?

    When two unrelated defaults clash, the compiler requires the class to override the method and resolve the conflict explicitly.
  4. 4. interface Shape { static Shape unit() { ... } } and class Square implements Shape. Which call compiles?

    Static interface methods are not inherited by implementing classes; you call them through the interface name.
  5. 5. Which of these can an interface NOT have?

    Interfaces have no per-object state; any field is a static constant. Use an abstract class when implementations need shared fields.

Summary

  • An interface declares capabilities; a class implements it and must provide public bodies for its abstract methods.
  • A class can implement many interfaces, and interfaces can extend several other interfaces. Program to interfaces in variable and parameter types.
  • Interface fields are public static final constants; don't create interfaces just to hold constants.
  • default methods (Java 8) let interfaces grow without breaking implementers. Conflicting defaults must be resolved by overriding, using X.super.method().
  • static methods (not inherited) provide factories and helpers; private methods (Java 9) share code inside the interface.
  • Marker interfaces such as Serializable, Cloneable and RandomAccess tag classes without adding methods.
  • Prefer an interface for the contract; add an abstract class when implementations share state or code.

Next: Composition, Aggregation and Association, where you'll build objects out of other objects instead of inheriting from them.