JavaSE-22.3.5【Lambda表达式支持的方法引用:引用构造器】

复制代码
 1 package day13.lesson3.p3;
 2 
 3 /*
 4 3.6 Lambda表达式支持的方法引用:引用构造器
 5 
 6     引用构造器,其实就是引用构造方法
 7 
 8     格式
 9         类名::new
10     范例
11         Student::new
12 
13     练习描述
14         定义一个类(Student),里面有两个成员变量(name,age),并提供无参构造方法和带参构造方法,以及成员变量对应的get和set方法
15         定义一个接口(StudentBuilder),里面定义一个抽象方法Student build(String name,int age);
16         定义一个测试类(StudentDemo),在测试类中提供两个方法
17             一个方法是:useStudentBuilder(StudentBuilder s)
18             一个方法是主方法,在主方法中调用useStudentBuilder方法
19  */
20 public class StudentDemo {
21     public static void main(String[] args) {
22         //Lambda表达式
23 //        useStudentBuilder((String name, int age) -> {
24 //            /*Student s = new Student(name, age);
25 //            return s;*/
26 //            return new Student(name, age);
27 //        });
28         useStudentBuilder((name, age) -> new Student(name, age));
29 
30         //方法引用之引用构造器
31         useStudentBuilder(Student::new);
32 
33         //Lambda被构造器替代时,它形式参数(name,age)全部传递给构造器(Student(String name, int age))作为参数
34     }
35 
36     private static void useStudentBuilder(StudentBuilder sb){
37         Student student = sb.build("amy", 24);
38         System.out.println(student.getName() + "," + student.getAge());
39     }
40 }
41 
42 class Student{
43     private String name;
44     private int age;
45 
46     public Student() {
47     }
48 
49     public Student(String name, int age) {
50         this.name = name;
51         this.age = age;
52     }
53 
54     public void setName(String name) {
55         this.name = name;
56     }
57 
58     public void setAge(int age) {
59         this.age = age;
60     }
61 
62     public String getName() {
63         return name;
64     }
65 
66     public int getAge() {
67         return age;
68     }
69 }
70 
71 interface StudentBuilder{
72     Student build(String name, int age);
73 }
复制代码

 

posted @   yub4by  阅读(70)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示