Java Stream How to - Create interface with default methods and adapter








Question

We would like to know how to create interface with default methods and adapter.

Answer

/*from ww  w . j  a  v  a  2 s .  c o m*/

public class Main {

  public static void main(String[] args) {
    //classic way
    ExampleAdapterSimple exampleSimple = new ExampleAdapterSimple();
    exampleSimple.a();

    //Default Method 
    ExampleInterface exampleDefault = new ExampleInterfaceDefault() {};
    exampleDefault.a();
  }

}
abstract class ExampleAdapter implements ExampleInterface {

  @Override
  public abstract void a();

  @Override
  public void b() {
    System.out.println("b");
  }

}
class ExampleAdapterSimple extends ExampleAdapter {

  @Override
  public void a() {
    System.out.println("a");
  }

}
interface ExampleInterface {
  
  void a();
  
  void b();

}
interface ExampleInterfaceDefault extends ExampleInterface {

  default void a() {
    System.out.println("a from ExampleInterfaceDefault");
  }
  
  default void b() {
    System.out.println("b from ExampleInterfaceDefault");    
  }
  
}

The code above generates the following result.