增强点

静态方法

public interface InterfacePlus {
    void run();
    static Date createDate(){
        return new Date();
    }
}

默认方法

public interface InterfacePlus {
    void run();
    default void sayHello()
    {
        System.out.println("Hello Java8!");
    }
}

其他

第一节开篇就说过,Java8采用注解@FunctionalInterface来保证接口为函数接口,即接口中只显式声明一个抽象方法,新增的静态方法和默认方法是否会影响其成为一个函数接口呢,并不会,原因是:静态方法和默认方法均为非抽象方法!
同理,复写父类的非抽象方法也不影响其成为一个函数接口,如复写equals方法,如下图所示:
Java8学习笔记(四)--接口增强

测试

静态方法测试

静态方法可以直接用接口来调用。

    Date date = InterfacePlus.createDate();
    System.out.println(date);

默认方法测试

非抽象的方法实现,只需要使用 default 关键字即可,这个特征又叫做扩展方法。在实现该接口时,该默认扩展方法在子类上可以直接使用,它的使用方式类似于抽象类中非抽象成员方法。

    /*自行实现后可直接调用default方法*/
        //子类实例化
        InterfacePlusImpl interfacePlusImpl = new InterfacePlusImpl();
        interfacePlusImpl.sayHello();
        //Lambda实例化
        InterfacePlus interfacePlus = System.out::println;
        interfacePlus.sayHello();

但扩展方法不能够重载 Object 中的方法。例如:toString、equals、 hashCode 不能在接口中被重载。
Java8学习笔记(四)--接口增强

参考

  1. Java 8 新特性概述

相关文章:

  • 2021-11-24
  • 2022-12-23
  • 2021-11-17
  • 2022-12-23
  • 2021-06-06
  • 2021-12-14
  • 2022-01-21
  • 2021-11-14
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-21
  • 2021-12-13
  • 2022-12-23
  • 2021-08-04
  • 2021-06-19
相关资源
相似解决方案