首页 > 其他分享 >函数式接口使用

函数式接口使用

时间:2024-05-29 10:58:52浏览次数:7  
标签:info String getInfo t2 T2 接口 使用 函数

1. 函数式接口定义
①单一抽象方法:函数式接口是只有一个抽象方法的接口(除了Object类中的方法外),除非你用default或static关键字标记它为默认方法或静态方法。
②@FunctionalInterface注解:虽然不是必需的,但可以使用@FunctionalInterface注解来明确标识一个接口为函数式接口。如果接口不符合函数式接口的定义(即包含多个抽象方法),编译器会报错。

2.实例展示
例子1
@FunctionalInterface
public interface T2 {
    String getInfo(String info);
}
public class T {
    public static void main(String[] args) {
        String s = getMyInfo(in -> in + "s");
        System.out.println(s);
    }

    private static String getMyInfo(T2 t2) {
        return t2.getInfo("info");
    }
}


例子2(例子1的变形,结果一样)
@FunctionalInterface
public interface T2 {
    String getInfo(String info);
}
public class T {
    public static void main(String[] args) {
        T2 t2 = in -> in + "s";
        System.out.println(t2.getInfo("info"));
    }
}

标签:info,String,getInfo,t2,T2,接口,使用,函数
From: https://www.cnblogs.com/l-liu/p/18219684

相关文章