函数型接口

    科技2024-05-29  79

    ##函数型接口

    如果接口中只有一个抽象类方法,则可以将其定义为函数型接口。此时,添加注解@FunctionalInterface即可。如以下两例:

    @FunctionalInterface //函数型接口,内部只有一个抽象类方法

    interface IComputer{     int add(int a,int b); }

    @FunctionalInterface //函数型接口,内部只有一个抽象类方法 interface Iprint{     void print(); }

    一般情况下,接口中的抽象方法需要先重写,再调用。

    IComputer computer = new IComputer() {             @Override             public int add(int a,int b) {                 return a+b;             } }; System.out.println(computer.add(1,2)); 

    在JDK8及以上版本中,匿名内部类也可用于Lambda表达式。

    IComputer computer = (a,b)->a+b;//接口类名 对象名  = ([参数列表])->返回值或输出语句; Iprint iprint = ()->System.out.println("Hello,World!");

    Processed: 0.013, SQL: 9