Interfaces and Default Methods

OOP · lesson 8 of 43 · 4 min read

How interfaces define capability, and how default and static methods let those contracts evolve safely.

Open this lesson in the learning hub

Key points

  • An interface is a contract: what a type can do, with no instance state attached. A class can implement many.
  • Methods are implicitly public abstract; fields are implicitly public static final constants.
  • default methods carry a body, so you can add a method without breaking every existing implementer.
  • static methods on interfaces make neat factories. List.of and Comparator.comparing are exactly that.
  • An interface with exactly one abstract method is a functional interface, so a lambda can implement it.
  • Defaults exist for evolution, not as a second inheritance path. Keep them thin and free of surprises.

Example

public class Main {
    interface Greeter {
        String name();                                    // the one abstract method

        default String greet() {                          // shared body, still overridable
            return "Hello, " + name() + "!";
        }

        static Greeter of(String name) {                  // static factory on the interface
            return () -> name;
        }
    }

    static class Shouter implements Greeter {
        @Override public String name() { return "world"; }

        @Override public String greet() {
            return Greeter.super.greet().toUpperCase();    // call the default explicitly
        }
    }

    public static void main(String[] args) {
        System.out.println(Greeter.of("Ada").greet());
        System.out.println(new Shouter().greet());
    }
}

Interfaces declare capability; default methods let published contracts grow without breakage.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.