Modern Java 8+ Features ยท Lambdas and Functional Interfaces

Default and Static Interface Methods

Since Java 8, interfaces can contain code: default methods that classes inherit or override, and static helper methods.

DefaultMethodsDemo.java

interface Greeter {
    String name();

    default String greet() {                 // a method with a body, inside an interface
        return "Hello, " + name() + "!";
    }

    static Greeter of(String n) {            // a static helper on the interface
        return () -> n;
    }
}

class LoudGreeter implements Greeter {
    public String name() { return "ben"; }

    public String greet() {                  // overrides the default
        return Greeter.super.greet().toUpperCase();
    }
}

public class DefaultMethodsDemo {
    public static void main(String[] args) {
        Greeter asha = Greeter.of("Asha");
        Greeter ben = new LoudGreeter();
        String a = asha.greet();
        String b = ben.greet();
        System.out.println(a + " " + b);
    }
}

Step by step

  1. Greeter.of is a static method on the interface. It returns a lambda that implements name().
  2. of() has finished, so its variables are gone.
  3. The value it returned, Greeter$Lambda/0x000000002d040488@2211cd19, is stored in asha.
  4. Java runs the LoudGreeter constructor to set up the new object.
  5. LoudGreeter() has finished, so its variables are gone.
  6. ben is created on the stack and points to a new LoudGreeter on the heap: {}.
  7. Java calls greet(). It gets its own variables on the stack.
  8. asha uses the default greet(), which calls name().
  9. lambda$of$0() has finished, so its variables are gone.
  10. greet() has finished, so its variables are gone.
  11. The value it returned, "Hello, Asha!", is stored in a.
  12. Java calls greet(). It gets its own variables on the stack.
  13. LoudGreeter overrides greet() but still reuses the default with Greeter.super.greet().
  14. Java calls name(). It gets its own variables on the stack.
  15. name() has finished, so its variables are gone.
  16. The method returns "Hello, " + name() + "!".
  17. greet() has finished, so its variables are gone.
  18. The value it returned, "HELLO, BEN!", is stored in b.
  19. It prints Hello, Asha! HELLO, BEN!.
  20. Both greeters share the interface's default greeting; one added its own twist.