s-day07-函数式接口的使用(将lambda作为实现类对象)

This commit is contained in:
2026-08-08 11:14:17 +08:00
parent 20598812d0
commit 9774ac3f0b
3 changed files with 73 additions and 4 deletions
@@ -10,6 +10,71 @@ package com.inmind.functional_interface02;
扩展:为何在一个接口中某些抽象方法不需要被重写??
在一个类中如果单继承和多实现,单继承的方法优先级高于接口中的方法定义,导致父类方法中
如果有跟接口中重名的方法实现的话,那么就相当于在子类中默认重写了接口的方法
-----------------------------------------------
函数式接口的使用:
函数式接口可以作为
参数类型
返回值类型
变量类型
其实就是将lambda表达式作为函数式接口的实现类对象
*/
public class Demo04 {
//函数式接口作为返回值类型
public static void main(String[] args) {
//获取一个函数式接口对象
MyFunctionalInterface impl = getInterface();
int value = getValue(impl, 10, 2);
System.out.println(value);
}
public static MyFunctionalInterface getInterface(){
//变量类型
/*MyFunctionalInterface impl = new MyFunctionalInterface() {
@Override
public int getValue(int a, int b) {
return a-b;
}
};*/
//变量类型
/*MyFunctionalInterface impl = (int a, int b)->{
return a-b;
};*/
// MyFunctionalInterface impl = ( a, b)-> a-b;
return ( a, b)-> a-b;
}
//---------------------------------------------------------------------------------
//函数式接口作为参数类型
public static void method1(String[] args) {
/*int result = getValue(new MyIFunctionalnterface() {
@Override
public int getValue(int a, int b) {
return a+b;
}
},10,2);*/
// int result = getValue((a, b) -> a + b, 10, 2);
int result = getValue((int a, int b) -> {return a + b;}, 10, 2);
System.out.println(result);
}
//接口回调:将我们的业务逻辑嵌入到源码方法中
public static int getValue(MyFunctionalInterface impl, int x, int y){
int result = impl.getValue(x, y);
return result;
}
}
@@ -0,0 +1,4 @@
package com.inmind.functional_interface02;
public class Demo05 {
}
@@ -1,13 +1,13 @@
package com.inmind.functional_interface02;
@FunctionalInterface
public interface MyIFunctionalnterface {
public interface MyFunctionalInterface {
// void method();
// void method(int a);
// int method(int a);
int method();
int getValue(int a,int b);
boolean equals(Object obj);
/*boolean equals(Object obj);
String toString();
int hashCode();
int hashCode();*/
}