JDK8新增接口的默认方法与静态方法

JDK8以前,interface中能够定义常量和抽象方法,访问修饰符是public。java

public interface A {
    /** a1和a2写法是等价的 */
    public static final int a1 = 0;

    int a2 = 0;

    /** methodA1和methodA2写法是等价的 */
    public abstract void methodA1();

    void methodA2();
}

 

JDK8起,容许咱们在interface中使用static和default修饰方法(使用这两种修饰符中其一就不能使用abstract修饰符),从而方法具备方法体。ide

public interface A {
    /** default访问修饰符修饰的方法 */
    default void methodB1() {
        System.out.println("this is default method");
    }

    /** static修饰符修饰的方法 */
    public static void methodB2() {
        System.out.println("this is static method");
    }
}

default修饰的方法,经过接口的实现类的对象调用;static修饰的方法,直接经过接口名调用。this

public class Test implements A{
    public static void main(String[] args) {

        /** 接口的default方法,经过接口的实现类的对象调用 */
        Test test = new Test();
        test.methodB1();

        /** 接口的静态方法,经过接口名调用 */
        A.methodB2();
    }
}

 

因为java支持一个实现类能够实现多个接口,若是多个接口中存在一样的static和default方法会怎么样呢?spa

  • 若是有两个接口中的static方法如出一辙,而且实现类同时实现了这两个接口,此时并不会产生错误,由于jdk8只能经过接口类调用接口中的静态方法,因此对编译器来讲是能够区分的。
  • 若是两个接口中定义了如出一辙的default方法,而且一个实现类同时实现了这两个接口,那么必须在实现类中重写默认方法,不然编译失败。
public interface A {
    /** default访问修饰符修饰的方法 */
    default void methodB1() {
        System.out.println("this is default method -- InterfaceA");
    }

    /** static修饰符修饰的方法 */
    public static void methodB2() {
        System.out.println("this is static method -- InterfaceA");
    }
}

public interface B{
    /** default访问修饰符修饰的方法 */
    default void methodB1() {
        System.out.println("this is default method -- InterfaceB");
    }

    /** static修饰符修饰的方法 */
    public static void methodB2() {
        System.out.println("this is static method -- InterfaceB");
    }
}

public class Test implements A,B{
    /** 因为A和B中default方法同样,因此这里必须覆盖 */
    @Override
    public void methodB1() {
        System.out.println("this is Overriding methods");
    }
    
    public static void main(String[] args) {

        /** 接口的default方法,经过接口的实现类的对象调用 */
        Test test = new Test();
        test.methodB1();

        /** A接口的静态方法,经过接口名调用 */
        A.methodB2();
        /** B接口的静态方法,经过接口名调用 */
        B.methodB2();
    }
}

运行结果:.net

  

 

参考: https://blog.csdn.net/aitangyong/article/details/54134385code

相关文章
相关标签/搜索