您的位置:首页 > 娱乐 > 明星 > 详细分析@FunctionalInterface的基本知识(附Demo)

详细分析@FunctionalInterface的基本知识(附Demo)

2025/8/5 21:03:01 来源:https://blog.csdn.net/weixin_47872288/article/details/140248049  浏览:    关键词:详细分析@FunctionalInterface的基本知识(附Demo)

目录

  • 前言
  • 1. 基本知识
  • 2. Demo

前言

Java的基本知识推荐阅读:

  1. java框架 零基础从入门到精通的学习路线 附开源项目面经等(超全)
  2. Spring框架从入门到学精(全)

1. 基本知识

@FunctionalInterface 是 Java 8 引入的一个注解,用于标记一个接口为函数式接口

函数式接口是只包含一个抽象方法的接口,可以有多个默认方法或静态方法,通常用于 lambda 表达式和方法引用

  • 标记接口为函数式接口,明确接口的设计意图,使代码更易读,便于他人理解接口的用途
  • 编译器会确保被标记的接口只有一个抽象方法。如果接口有多于一个抽象方法,编译器会报错,从而避免接口被错误地使用

2. Demo

基本的使用法则如下:

定义函数式接口以及使用lambda

@FunctionalInterface
interface MyFunctionalInterface {void myMethod();
}public class FunctionalInterfaceDemo {public static void main(String[] args) {MyFunctionalInterface func = () -> System.out.println("Hello, Functional Interface!");func.myMethod();}
}

多个默认方法和静态方法

@FunctionalInterface
interface MyFunctionalInterface {void myMethod();// 默认方法default void defaultMethod() {System.out.println("This is a default method.");}// 静态方法static void staticMethod() {System.out.println("This is a static method.");}
}public class FunctionalInterfaceDemo {public static void main(String[] args) {MyFunctionalInterface func = () -> System.out.println("Hello, Functional Interface!");func.myMethod();func.defaultMethod();MyFunctionalInterface.staticMethod();}
}

为了进一步说明此注解的主要性:(编译检查)

加上注解:

在这里插入图片描述

给一个实际的Demo例子如下:

// 定义函数式接口
@FunctionalInterface
interface CorrectFunctionalInterface {void singleMethod();// 可以有默认方法default void defaultMethod() {System.out.println("This is a default method.");}// 可以有静态方法static void staticMethod() {System.out.println("This is a static method.");}
}// 具体使用
public class FunctionalInterfaceDemo {public static void main(String[] args) {// 使用 lambda 表达式实现 singleMethodCorrectFunctionalInterface func = () -> System.out.println("Hello from singleMethod!");// 调用 singleMethodfunc.singleMethod();// 调用默认方法func.defaultMethod();// 调用静态方法CorrectFunctionalInterface.staticMethod();}
}

截图如下:

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com