lambda构造器引用

上节我们学习了解了方法引用,今天我们接着学构造器引用,废话不多说,直接怼代码
1.示例代码
public class Employee {
    

    private int id;
    private String name;
    private int age;
    private double salary;

    public Employee() {
    }

    public Employee(String name) {
        this.name = name;
    }

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Employee(int id, String name, int age, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }


    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]";
    }
2.方法测试类以及对应代码片段的解释
public class Test {
    
    public static void main(String[] args) {
        
        /**
         * 构造引用:构造器的参数列表,需要与函数式接口中参数列表保持一致!
         * 类名 :: new
         * 注意:接口的抽象方法的参数和返回值必须和实例方法的参数和返回值类型保持一致
         */
        Supplier sup = () -> new Employee();        //普通的lambda表达式
        System.out.println(sup.get());          
      -----------------------------------------------------------------------
        Supplier sup2 = Employee::new;     //lambda方法引用方式
        System.out.println(sup2.get());
         
         
         
    
    }

你可能感兴趣的:(lambda构造器引用)