Java Stream How to - Call default method from interface








Question

We would like to know how to call default method from interface.

Answer

//  w w w . j  a v  a2  s .  c o m
public class Main {
  public static void main(String[] args) {
    MyCalculator calculator = new MyCalculator();
    System.out.println(calculator.multiply(1, 2));
  }
}

class MyCalculator implements Calculator {
  @Override
  public int add(int a, int b) {
    return a + b;
  }

  @Override
  public int subtract(int a, int b) {
    return 0;
  }
}

interface Calculator {
  int add(int a, int b);

  int subtract(int a, int b);

  default int multiply(int a, int b) {
    return a * b;
  }
}

The code above generates the following result.