Java Reference
In-Depth Information
The output is shown here:
In the program, pay special attention to this line:
Here, a reference to the
static
method
isPrime( )
is passed as the first argument to
numTest( )
. This works because
isPrime
is compatible with the
IntPredicate
functional
interface. Thus, the expression
MyIntPredicates::isPrime
evaluates to a reference to an
object in which
isPrime( )
provides the implementation of
test( )
in
IntPredicate
. The oth-
er two calls to
numTest( )
work in the same way.
Method References to Instance Methods
A reference to an instance method on a specific object is create by this basic syntax:
objRef
::
methodName
As you can see, the syntax is similar to that used for a
static
method, except that an object
reference is used instead of a class name. Thus, the method referred to by the method ref-
erence operates relative to
objRef
. The following program illustrates this point. It uses the
same
IntPredicate
interface and
test( )
method as the previous program. However, it cre-
ates a class called
MyIntNum
, which stores an
int
value and defines the method
isFactor(
)
, which determines if the value passed is a factor of the value stored by the
MyIntNum
in-
stance. The
main( )
method then creates two
MyIntNum
instances. It then calls
numTest(
)
, passing in a method reference to the
isFactor( )
method and the value to be checked. In
each case, the method reference operates relative to the specific object.