Java 8 允许我们使用default关键字,为接口声明添加非抽象的方法实现。这个特性又被称为扩展方法
sample:
interface Formula {
double calculate(int a);
default double sqrt(int a) {
return Math.sqrt(a);
}
}
public class InterfaceTest {
public static void main(String[] args) {
Formula formula = new Formula() {
@Override
public double calculate(int a) {
return sqrt(a * 100);
}
};
double calculate = formula.calculate(100); // 100.0
double sqrt = formula.sqrt(16);
System.out.println(calculate);
System.out.println(sqrt);
}
}