方法引用_通过类名引用静态成员方法和方法引用_通过super引用父类的成员方法

方法引用_通过类名引用静态成员方法

由于在java.lang.Math类中已经存在了静态方法abs,所以我们需要通过Lambda来调用该方法时,有两种写法

@FunctionalInterface
public interface Calcable {
    //定义一个抽象方法,传递一个整数,对整数进行绝对值计算并返回
    int calsAbs(int number);
}
/*
    通过类名引用静态成员方法
    类已经存在,静态成员方法也已经存在
    就可以通过类名直接引用静态成员方法
 */
public class DMethodReference {
    public static void main(String[] args) {
        //调用method方法,传递计算绝对值得整数,和Lambda表达式
        int number = method(-10,(n)->{
            //对参数进行绝对值得计算并返回结果
            return Math.abs(n);
        });
        System.out.println(number);
        /*
        使用方法引用优化Lambda表达式
         */
        int method = method(-10, Math::abs);
        System.out.println(method);
    }
    //定义一个方法,方法的参数传递要计算绝对值的整数,和函数式接口Calcable
    public static int method(int number,Calcable c){
        return c.calsAbs(number);
    }
}

方法引用_通过super引用父类的成员方法

如果存在继承关系,当Lambda中需要出现super调用时,也可以使用方法引用进行替代。

/*
定义见面的函数式接口
 */
@FunctionalInterface
public interface Greetable {
    //定义一个见面的方法
    void greet();
}
/*
定义父类
 */
public class Human {
    //定义一个sayHello方法
    public void sayHello(){
        System.out.println("Hello 我是Human!");
    }
}
/*
定义子类
 */
public class Man extends Human{
    //子类重写父类方法
    @Override
    public void sayHello() {
        System.out.println("Hello 我是Man");
    }
    //定义一个方法参数传递Greetable接口
    public void method(Greetable g){
        g.greet();
    }
    public void show(){
        //调用method方法,方法的参数Greetable是一个函数式接口,所以可以传递Lambda
        /*method(()->{
            //创建父类Human对象
            Human h = new Human();
            //调用父类的sayHello方法
            h.sayHello();
        });*/

        //因为有子父类关系,所以存在的一个关键字super,代表父类,所以我们可以直接使用super调用父类的成员方法
        /*method(()->{
            super.sayHello();
        });*/

        /*
            使用super引用类的成员方法
            super是已经存在的
            父类的成员方法sayHello也是已经存在的
            所以我们可以直接使用super引用父类的成员方法
         */
        method(super::sayHello);
    }

    public static void main(String[] args) {
        new Man().show();
    }
}

 

posted @ 2022-07-21 13:42  魔光领域  阅读(35)  评论(0编辑  收藏  举报