构造函数和函数式接口

此处,讲述构造函数有0  、 1 、2 、3 (需要自己定义相应的函数式接口)个参数的时候,应该使用的函数式接口:

构造方法引用: Class::new

首先,定义Apple对象,并定义有0  、 1 、2 、3个参数的构造函数:

public class Apple {

public Apple() {
System.out.println("Constructor without parameter");
}

public Apple(double weight) {
this.weight = weight;
System.out.println("Constructor with 1 parameter: weight");
}

public Apple(String location, double weight) {
this.location = location;
this.weight = weight;
System.out.println("Constructor with 2 parameters: location and weight");
}

public Apple(String location, double weight, String color) {
this.location = location;
this.weight = weight;
this.color = color;
System.out.println("Constructor with 3 parameters: location and weight and color");
}

private String location;
private double weight;
private String color;

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public double getWeight() {
return weight;
}

public void setWeight(double weight) {
this.weight = weight;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

}

 

如下是当构造函数有0 、 1 、 2 、3 个 参数时,使用函数式接口测试调用相应构造方法的例子:


import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;


public class AppleTest {


public static void main(String[] args) {


//等价于Supplier<Apple> c1 = () -> new Apple();
//指向new Apple()的构造函数引用
Supplier<Apple> c1 = Apple::new;
Apple a1 = c1.get();

//指向Apple(Double weight)的构造函数引用
//R apply(T t);
Function<Double, Apple> c2 = Apple::new;
Apple a2 = c2.apply(10.0);

//指向Apple(String location, Double weight)的构造函数引用
// R apply(T t, U u);
BiFunction<String, Double, Apple> c3 = Apple::new;
Apple a3 = c3.apply("Beijing", 12.0);

//指向 Apple(String location, double weight, String color)的构造函数引用
//R apply(T t, U u, V v);
TriFunction<String, Double, String, Apple> c4 = Apple::new;
Apple a4 = c4.apply("Beijing", 12.0, "Red");

}


}

 

其中,当我们需要使用函数式接口调用有 3 个参数的构造函数时,需要定义如下函数式接口:

public interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}

 

如下是AppleTest 的运行结果:

 

posted @ 2019-12-03 12:41  Happy2Share  阅读(439)  评论(0编辑  收藏  举报