Java Reference
In-Depth Information
a functional interface. There are different types of method references. We will begin with
method references to static methods.
Method References to static Methods
A method reference to a static method is created by specifying the method name preceded
by its class name, using this general syntax:
ClassName :: methodName
Notice that the class name is separated from the method name by a double colon. The ::
is a new separator that has been added to Java by JDK 8 expressly for this purpose. This
method reference can be used anywhere in which it is compatible with its target type.
The following program demonstrates the static method reference. It does so by first de-
claring a functional interface called IntPredicate that has a method called test( ) . This
method has an int parameter and returns a boolean result. Thus, it can be used to test an in-
teger value against some condition. The program then creates a class called MyIntPredic-
ates , which defines three static methods, with each one checking if a value satisfies some
condition. The methods are called isPrime( ) , isEven( ) , and isPositive( ) , and each meth-
od performs the test indicated by its name. Inside MethodRefDemo , a method called
numTest( ) is created that has as its first parameter, a reference to IntPredicate . Its second
parameter specifies the integer being tested. Inside main( ) , three different tests are per-
formed by calling numTest( ) , passing in a method reference to the test to perform.
Search WWH ::




Custom Search