Referencing a constructor uses the syntax: classname::new.
Can be assigned to a functional interface that has a constructor-compatible method.
Example with Parameterized Constructor
MyFunc myClassCons = MyClass::new;
MyClass mc = myClassCons.func("Testing");
Example with Default Constructor
MyFunc2 myClassCons = MyClass::new;
MyClass mc = myClassCons.func();
Use with Generic Classes
MyGenClass
Type Inference
// Demonstrates a constructor reference.
// MyFunc is a functional interface whose method returns
// a MyClass reference.
MyFunc interface {
MyClass func(String s);
}
class MyClass {
private String str;
// This constructor takes one argument.
MyClass(String s) { str = s; }
// This is the default constructor.
MyClass() { str = ""; }
// ...
String getStr() { return str; }
}
class ConstructorRefDemo {
public static void main(String args[])
{
// Creates a reference to the constructor of MyClass.
// Since MyFunc's func() method takes one argument,
// new references the parameterized constructor of MyClass
// and not the default constructor.
MyFunc myClassCons = MyClass::new; A constructor reference
// Creates an instance of MyClass using this constructor reference.
MyClass mc = myClassCons.func("Testing");
// Use the newly created MyClass instance.
System.out.println("str in mc is " mc.getStr());
}
}
The above is the detailed content of Builder references. For more information, please follow other related articles on the PHP Chinese website!