JDK1.8新特性之接口中的静态方法与默认方法

一. 新特性概述概述

在Jdk8之前,Interface之中可以定义变量和方法,变量必须为public static final的,由于实现接口中的方法必须要重写它的方法,而子类继承抽象类必须重写其所有的抽象方法,所以接口中的方法必须隐式为public abstract的。JDK1.8中允许我们在接口中定义static方法和default方法

二. 代码示例

Jdk8之前,接口中只能有public abstract隐式修饰的抽象方法。

public interface JDK8BeforeInterface {
    
    public static final int field1 = 0;

    public abstract void method1(int a) throws Exception;

    //隐式的被public abstract修饰
    void method2(int a) throws Exception;
}

Jdk8及以后,允许我们在接口中定义static方法和default方法。

public  interface JDK8Interface {

    //static 修饰定义静态方法
    static void staticMethod(){

       System.out.println("接口中的静态方法。");
    }
    //default修饰符定义默认方法
    default void defaultMethod() {

        System.out.println("接口中的默认方法。");
    }
}

代码解析:

public interface JDK8Interface {

        //static 修饰定义静态方法

        static void staticMethod() {

                System.out.println("接口中的静态方法。");

        }

        //default修饰符定义默认方法 

        default void defaultMethod() {

                 System.out.println("接口中的默认方法。");

        }

}

 

定义一个接口的实现类:

public class JDK8InterfaceImpl implements JDK8Interface {

//实现接口后,因为默认方法不是抽象方法,所以可以不重写,但是如果开发需要,也可以重写。

}

静态方法,只能通过接口名来调用,不可以通过实现类的类名或者实现类的对象来调用。default方法,只能够通过接口实现类的对象来调用。

public class Main {

        public static void main(String[] args) {

        //static方法必须通过接口类来调用,不可以通过实现类或者是实现类的对象来调用

        JDK8Interface.staticMethod();

        //default方法必须通过实现类的对象来调用

        new JDK8InterfaceImpl().defaultMethod();

         }

}

 

当然如果接口中的默认方法不能满足某个实现类需要,那么实现类可以覆盖默认方法。

public class AnOtherJDK8InterfaceImpl implements JDK8Interface {

        @Override

         public void deaultMethod() {

                  System.out.println("接口实现类覆盖了接口中的default方法");

        }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章