Java 8引入了接口中默认方法实现的新概念。添加此功能是为了实现向后兼容性,因此可以使用旧接口来利用Java 8的lambda表达功能。
例如,“列表”或“集合”接口没有“ forEach”方法声明。因此,添加这种方法将简单地破坏收集框架的实现。Java 8引入了默认方法,以便List / Collection接口可以具有forEach方法的默认实现,并且实现这些接口的类不必实现相同的方法。
public class Java8Tester {
public static void main(String args[]) {
Vehicle vehicle = new Car(); vehicle.print();
}
}
interface Vehicle {
default void print() {
System.out.println("我是车!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
interface FourWheeler {
default void print() {
System.out.println("我是四轮车!");
}
}
class Car implements Vehicle, FourWheeler {
public void print() {
Vehicle.super.print();
FourWheeler.super.print();
Vehicle.blowHorn();
System.out.println("我是车!");
}
}输出结果
我是车! 我是四轮车! Blowing horn!!! 我是车!