上节我们学习了解了方法引用,今天我们接着学构造器引用,废话不多说,直接怼代码
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<Employee> sup = () -> new Employee(); //普通的lambda表达式
System.out.println(sup.get());
-----------------------------------------------------------------------
Supplier<Employee> sup2 = Employee::new; //lambda方法引用方式
System.out.println(sup2.get());
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。