通过类名引用静态成员方法
类名已经存在,静态成员也已近存在
就可以通过类直接引用静态成员方法
代码如下:
@FunctionalInterface public interface Calcable { int calsAbs(int number); }
public static int method(int number,Calcable c){ return c.calsAbs(number); } public static void main(String[] args) { int method = method(-10, (n) -> { return Math.abs(n); }); System.out.println(method);
使用方法引用优化Lambda表达式
Math类是存的
abs计算绝对值的静态方法也是已经存在的
所以我们可以直接类名引用静态方法
int method1 = method(-10, Math::abs); System.out.println(method1) ;
方法引用_通过super引用父类的成员方法
实现代码:
/* 定义见面的函数式接口 */ @FunctionalInterface public interface Greetable { //定义一个见面的方法 void greet(); }
/* 定义父类 */ public class Human { //定义一个sayHello的方法 public void sayHello(){ System.out.println("Hello 我是Human"); } }
/** * 定义子类 */ public class Man extends Human{ //子类重写父类sayHello的方法 @Override public void sayHello() { System.out.println("Hello 我是Man!"); } //定义一个方法参数传递Greetable接口 public void method(Greetable g){ g.greet(); } public void method(){ //调用method方法,方法的参数Greetable是一个函数式接口,所以可以传递Lambda // method(()->{ // Human human = new Human(); // human.sayHello(); // }); //因为有子父类关系,所以存在的一个关键字super,代表父类,所以我们可以直接使用super调用父类的成员方法 // method(()->{ // super.sayHello(); // }); /* 使用super引用类的成员方法 super是已经存在的 父类的成员方法sayHello也是已经存在的 所以我们可以使用super引用父类的成员方法 */ method(super::sayHello); } public static void main(String[] args) { new Man().sayHello(); }