Java8之前要求接口中必须都是抽象方法,Java8中允许接口中包含默认类方法及静态的类方法。
default方法
- 接口中可以定义多个default方法;
interface A {
default void same(){
System.out.println("a");
}
default void same2(){
System.out.println("a2");
}
}
- default方法为非静态方法,只能在实现类中调用;
interface A {
default void same(){
System.out.println("a");
}
}
class C implements A {
public static void main(String [] args){
C c = new C();
c.same(); //a
}
}
- 类C实现了AB两个接口,接口AB中都存在相同定义的default方法,则类C必须覆盖default方法@Override,在覆盖的方法中,可以调用接口中方法,A.super.method1()或B.super.method1();
interface A {
default void same(){
System.out.println("a");
}
}
interface B {
default void same(){
System.out.prin