Java Reference
In-Depth Information
This program produces the following output:
In the program, pay special attention to the line:
Here, the method reference assigned to ip refers to an instance method isFactor( ) on
myNum . Thus, when test( ) is called through that reference, as shown here:
the method will call isFactor( ) on myNum , which is the object specified when the
method reference was created. The same situation occurs with the method reference
myNum2::isFactor , except that isFactor( ) will be called on myNum2 . This is confirmed
by the output.
It is also possible to handle a situation in which you want to specify an instance method
that can be used with any object of a given class—not just a specified object. In this case,
you will create a method reference as shown here:
ClassName :: instanceMethodName
Here, the name of the class is used instead of a specific object, even though an instance
method is specified. With this form, the first parameter of the functional interface matches
the invoking object and the second parameter matches the parameter (if any) specified
by the method. Here is an example. It reworks the previous example. First, it replaces
IntPredicate with the interface MyIntNumPredicate . In this case, the first parameter to
test( ) is of type MyIntNum . It will be used to receive the object being operated upon. This
allows the program to create a method reference to the instance method isFactor( ) that can
be used with any MyIntNum object.
Search WWH ::




Custom Search