Java Reference
In-Depth Information
The first specifies a parameter of type String . The second is the default, parameterless con-
structor. Now, examine the following line:
Here, the expression MyClass::new creates a constructor reference to a MyClass con-
structor. In this case, because MyFunc 's func( ) method takes a String parameter, the
constructor being referred to is MyClass(String s) because it is the one that matches.
Also notice that the reference to this constructor is assigned to a MyFunc reference called
myClassCons . After this statement executes, myClassCons can be used to create an in-
stance of MyClass , as this line shows:
In essence, myClassCons has become another way to call MyClass(String s) .
If you wanted MyClass::new to use MyClass 's default constructor, then you would
need to use a functional interface that defines a method that has no parameter. For example,
if you define MyFunc2 , as shown here:
then the following line will assign to MyClassCons a reference to MyClass 's default (i.e.,
parameterless) constructor:
In general, the constructor that will be used when ::new is specified is the one whose para-
meters match those specified by the functional interface.
Ask the Expert
Q :
Can I declare a constructor reference that creates an array?
A : Yes. To create a constructor reference for an array, use this construct:
Search WWH ::




Custom Search