Lambda_05 函数表达式引用构造方法
声明接口,接口作为对象的生成器
声明接口
@FunctionalInterface
interface PersonInterface1 {
public Person interfaceFun();
}
@FunctionalInterface
interface PersonInterface2 {
public Person interfaceFun(String name);
}
@FunctionalInterface
interface PersonInterface3 {
public Person interfaceFun(String name, Integer age);
}
调用函数式接口,匿名函数调用。
public static void main(String[] args) {
//函数式接口 实现无参数构造方法 方法1
PersonInterface1 intf0 = () -> {
return new Person();
};
intf0.interfaceFun();
//函数式接口 实现无参数构造方法 方法2 (方法1的简写)
PersonInterface1 intf1 = () -> new Person();
intf1.interfaceFun();
//函数式接口实现一个参构造方法
PersonInterface1 intf2 = () -> new Person("小明");
intf2.interfaceFun();
//函数式接口实现多个参构造方法
PersonInterface1 intf3 = () -> new Person("小明",16);
intf3.interfaceFun();
}
创建对象的形式 类名::new
interfaceName intf = class::new;
intf.fun(); 根据接口入参分别实现不同的构造方法。
public static void main(String[] args) {
//使用 class::new 实现
PersonInterface1 intf4 = Person::new;
intf4.interfaceFun();
PersonInterface2 intf5 = Person::new;
intf5.interfaceFun("小武");
PersonInterface3 intf6 = Person::new;
intf6.interfaceFun("小帅哥",18);
}
调用接口的方法可以返回该对象的实例
代码展示
public class Lambda6 {
public static void main(String[] args) {
//函数式接口 实现无参数构造方法 方法1
PersonInterface1 intf0 = () -> {
return new Person();
};
intf0.interfaceFun();
//函数式接口 实现无参数构造方法 方法2 (方法1的简写)
PersonInterface1 intf1 = () -> new Person();
intf1.interfaceFun();
PersonInterface1 intf2 = () -> new Person("小明");
intf2.interfaceFun();
PersonInterface1 intf3 = () -> new Person("小明",16);
intf3.interfaceFun();
//使用 class::new 实现
PersonInterface1 intf4 = Person::new;
intf4.interfaceFun();
PersonInterface2 intf5 = Person::new;
intf5.interfaceFun("小武");
PersonInterface3 intf6 = Person::new;
intf6.interfaceFun("小帅哥",18);
}
}
@FunctionalInterface
interface PersonInterface1 {
public Person interfaceFun();
}
@FunctionalInterface
interface PersonInterface2 {
public Person interfaceFun(String name);
}
@FunctionalInterface
interface PersonInterface3 {
public Person interfaceFun(String name, Integer age);
}
class Person {
private String name;
private Integer age;
Person() {
System.out.println("无参数构造函数");
}
public Person(String name) {
this.name = name;
System.out.println("一个参数构造函数,name:" + name);
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
System.out.println("有二个参数构造函数,name:" + name + ",age:" + age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}