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