Java8 中的接口

来源:互联网 发布:室内设计软件培训 编辑:程序博客网 时间:2024/06/08 08:02

Java8 中的接口发生了一些变化,具体的变化如下:

       1.提供了静态方法和默认方法,分别使用static 和default 关键字修饰,这两种方法可以有方法体(下面是需要注意的地方)。
           [1]:default 方法属于实例,static 方法属于接口或类。要注意的是:default 方法可以被继承,static 方法不会。
           [2]:如果一个类实现了多个接口,并且这些接口之间没有相互继承关系,同时存在相同的 default 方法时会报错,不过你可以在实现类中重写default 方法并通过<接口>.super.<方法名>(); 形式指定调用哪个父接口中的default 方法。
       2.如果一个接口只有一个抽象方法,那么这个接口会默认自动变成函数式接口。
       3.如果使用了@FunctionalInterface 注解对接口进行修饰,说明这个接口是一个函数式接口,在该接口只能有一个抽象方法(不限制静态方法和默认方法)。一个函数式接口可以通过Lambda 表达式来创建该接口的对象。

      下面是一个关于Java8 中接口的一个简单示例:在接口中定义了一个static 方法与一个default 方法,这两个方法都可以有独立的方法体,打破了以前只能在接口中定义抽象方法的规则。通过一个Test 类去实现TestInterface 接口,Test 类的实例可以调用testDefaultMethod() 方法但是不能调用testStaticMethod() 方法,如果想调用testStaticMethod() 方法可以通过使用接口的名字直接调用静态方法。

public interface TestInterface {    static void testStaticMethod(){        System.out.println("static method run");    }    default void testDefaultMethod(){        System.out.println("default method run");    }}class Test implements TestInterface {    public static void main(String[] args) {        Test test = new Test();        test.testDefaultMethod();        //test.testStaticMethod();  Static method may be invoked on containing interface class only        TestInterface.testStaticMethod();   //对于接口中的静态方法可以使用接口名直接调用    }}

输出
default method run
static method run

      如果一个类实现了两个接口,这两个接口之间没有继承关系,并且这两个接口中有相同的默认方法,那么你在实现它们两个的时候必须要重写其中的默认方法,可以在重写的方法中调用指定接口中的默认方法,否则会报错。

public interface TestInterface {    default void testDefaultMethod(){        System.out.println("TestInterface default method run");    }}interface TestInterface1{    default void testDefaultMethod(){        System.out.println("TestInterface1 default method run");    }}class Test implements TestInterface,TestInterface1 {    public void testDefaultMethod(){        TestInterface1.super.testDefaultMethod();    }    public static void main(String[] args) {        Test test = new Test();        test.testDefaultMethod();    }}

输出
TestInterface1 default method run

      定义函数式接口的方式有两种,一种是定义一个接口并且在该接口中只有一个抽象方法;第二种方式是使用@FunctionalInterface 注解声明该接口是一个函数式接口,一旦加了@FunctionalInterface 注解那么在该接口中只能定义一个抽象方法,定义多了或者不定义会报错。

@FunctionalInterfacepublic interface TestFunctionalInterface {    static void staticMethod(){}    //在函数式接口中不限制定义静态方法与默认方法    default void defaultMethod(){}    void functionalInterfaceMethod();    // void functionalInterfaceMethod2(); 不允许}
原创粉丝点击