构造函数参考
构造函数引用有助于指向构造函数方法。使用“::new”符号访问构造函数引用。
//Constructor reference Factory vehicle_factory = Vehicle::new;
以下示例显示了构造函数引用在 Java 8 及以后版本中的工作原理。
interface Factory { Vehicle prepare(String make, String model, int year); } class Vehicle { private String make; private String model; private int year; Vehicle(String make, String model, int year){ this.make = make; this.model = model; this.year = year; } public String toString(){ return "Vehicle[" + make +", " + model + ", " + year+ "]"; } } public class FunctionTester { static Vehicle factory(Factory factoryObj, String make, String model, int year){ return factoryObj.prepare(make, model, year); } public static void main(String[] args) { //Constructor reference Factory vehicle_factory = Vehicle::new; Vehicle carHonda = factory(vehicle_factory, "Honda", "Civic", 2017); System.out.println(carHonda); } }
输出
Vehicle[Honda, Civic, 2017]