方法引用-通过类名引用静态成员方法和通过super引用父类的成员方法
方法引用-通过类名引用静态成员方法
Calcable类
@FunctionalInterface public interface Calcable { //定义一个抽象方法,传递一个整数,对整数进行绝对值计算并返回 int calsAbs(int number); }
Demo01StaticMethodRerfecence类
/* 通过类名引用静态成员方法 类已经存在,静态成员方法也已经存在 就可以通过类名直接引用静态成员方法 */ public class Demo01StaticMethodRerfecence { //定义一个方法,方法的参数传递要计算绝对值的整数,和函数式接口Calcable public static int method(int number,Calcable c){ return c.calsAbs(number); } public static void main(String[] args) { //调用method方法,传递借宿那绝对值得整数,和Lambda表达式 int number = method(-10,(n)->{ return Math.abs(n); }); System.out.println(number); /* 使用方法引用优化Lambda表达式 Math类是存在的 abs计算绝对值的静态方法也是已经存在的 所以哦我们可以直接通过类名引用静态方法 */ int number2 = method(-10,Math::abs); System.out.println(number2); } }
方法引用-通过super引用父类的成员方法
Greetable接口
@FunctionalInterface public interface Greetable { //定义一个见面的方法 void greet(); }
Human父类
/* 定义一个父类 */ public class Human { //定义一个sayHello方法 public void sayHello(){ System.out.println("Hello,我是Human!"); } }
Man子类
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 shwo(){ //调用method方法,方法的参数Greetable是一个函数式接口,所以可以传递Lambda method(()->{ //创建父类Human对象 Human human = new Human(); //调用父类的sayHello方法 human.sayHello(); }); //因为有子父类关系,所以存在一个关键字super,代表父类,所以我们可以直接使用super调用父类的成员方法 method(()->{ super.sayHello(); }); /* 使用super引用类的成员方法 super是已经存在的 父类的成员方法sayHello也是已经存在的 所以我们可以直接使用super引用父类的成员方法 */ method(super::sayHello); } public static void main(String[] args) { new Man().shwo(); }

浙公网安备 33010602011771号