java 8 新特性(3.接口的默认方法和静态方法)

java8中允许使用default关键字定义接口的默认方法,默认方法与抽象方法不同,不需要被实现类来具体实现,但是可以被实现类继承或重写。默认方法的出现提供了在不破坏接口的兼容性的前提下对接口进行扩展。

java8中使用static关键字定义接口的静态方法,与一般java类中的静态方法一样。

public interface AA {

    static void helloWorld(){
        System.out.println("hello world");
    }

    default void doSomething(){
        System.out.println("doSomething in AA");
    }
}
public interface BB {

    default void doSomething(){
        System.out.println("doSomething in BB");
    }
}
public interface CC extends AA,BB{
    //重新了父接口的默认方法
    default void doSomething(){
        System.out.println("doSomething in CC");
        //只有直接父类才可以通过XX.super.xxMethod()的方式调用父类默认方法
        AA.super.doSomething();
        BB.super.doSomething();
    }
}
public class Test1 implements CC{

    public static void main(String[] args) {
        CC cc = new Test1();
        //调用接口的默认方法
        cc.doSomething();
        //调用接口的静态方法
        AA.helloWorld();
    }
}
执行结果:

doSomething in CC
doSomething in AA
doSomething in BB
hello world





你可能感兴趣的:(java,java8,接口,默认方法,静态方法)