jdk1.8新特性 方法引用

本文深入探讨了Java中方法引用的概念,包括通过对象名、类名、super、this以及构造器和数组的引用方式,展示了如何简化lambda表达式,提高代码的可读性和效率。

1.方法引用
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
2.通过对象名引用方法
在这里插入图片描述

public interface Printable {
    void print(String s);
}
public class MethodRerObject {
    public void printUpp(String s){
        System.out.println(s.toUpperCase());
    }
}
 public static void pringString(Printable p){
        p.print("Hello");
    }

    public static void main(String[] args) {
        pringString((s)->{
            MethodRerObject mr=new MethodRerObject();
            mr.printUpp(s);
        });
        //使用方法引用来优化
        pringString(new MethodRerObject()::printUpp);
    }

3.通过类名引用静态方法
使用前提:类已经存在,静态成员方法已经存在

@FunctionalInterface
public interface Calcable {
    int calsabs(int a);
}
public class Demo02 {
    public static int method(int number, Calcable c){
        return c.calsabs(number);
    }

    public static void main(String[] args) {
        method(-10,(n)->{
            return Math.abs(n);
        });
        //利用方法引用简化
        method(-10,Math::abs);
    }
}

4.通过super引用父类成员方法

@FunctionalInterface
public interface Greetable {
    void greet();

}
public class Human {
    public void sayHello(){
        System.out.println("hello");
    }
}
public class Man extends  Human {
    public void sayHello(){
        System.out.println("hello,我是man");
    }
    public void method(Greetable g){
        g.greet();
    }
    public void show(){
        method(()->{
            Human hm=new Human();
            hm.sayHello();
        });
        //简化lambda表达式
        method(()-> super.sayHello());
        //利用super引用父类的方法
        method(super::sayHello);
    }
}

5.通过this引用本类成员
method(this::sayHello);

6.类的构造器引用

@FunctionalInterface
public interface PersonBuilder {
    Person buildP(String name);
}

public static void build(String name,PersonBuilder p){
        Person person = p.buildP(name);
        System.out.println(person.getName());

    }

    public static void main(String[] args) {
        build("张洒",(String name)->{
            return new Person(name);
        });
        build("李四",Person::new);
    }

7.数组的构造器引用
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值