进阶day06-函数式接口的使用
This commit is contained in:
@@ -9,6 +9,51 @@ package com.inmind.functional_interface02;
|
||||
扩展:为何在一个接口中某些抽象方法不需要被重写??比如Comparator接口
|
||||
在一个类中如果单继承和多实现,单继承的方法优先级高于接口中的方法定义,导致父类方法中
|
||||
如果有跟接口中重名的方法实现的话,那么就相当于在子类中默认重写了接口的方法
|
||||
------------------------------------------------------------------
|
||||
函数式接口的使用:
|
||||
1.作为参数
|
||||
2.作为返回值
|
||||
|
||||
*/
|
||||
public class Demo04 {
|
||||
public static void main(String[] args) {
|
||||
//匿名内部类的方式来调用getValue()方法
|
||||
/*int value = getValue(new MyInterface() {
|
||||
@Override
|
||||
public int getSum(int a, int b) {
|
||||
return a+b;
|
||||
}
|
||||
}, 10, 20);*/
|
||||
// int value = getValue((int a, int b)->{return a+b;},10,20);
|
||||
int value = getValue((a, b)-> a+b,10,20);
|
||||
System.out.println("运行结果1:"+value);
|
||||
//------------------------------------------
|
||||
MyInterface instance = getInstance();
|
||||
int result = instance.getSum(10, 20);
|
||||
System.out.println("运行结果2:"+result);
|
||||
}
|
||||
//定义出一个函数式接口作为返回值类型,参数列表定义为无参的静态方法
|
||||
public static MyInterface getInstance(){
|
||||
/*MyInterface myInterface = new MyInterface() {
|
||||
@Override
|
||||
public int getSum(int a, int b) {
|
||||
return a*b;
|
||||
}
|
||||
};*/
|
||||
// MyInterface myInterface =(int a, int b)->{return a*b;};
|
||||
// MyInterface myInterface =( a, b)-> a*b;
|
||||
return (a, b)-> a*b;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//定义出一个有整数返回值,参数列表是函数式接口,2个整数的静态方法
|
||||
public static int getValue(MyInterface myInterface, int a, int b) {
|
||||
int sum = myInterface.getSum(a, b);
|
||||
return sum;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user