I'm also learning from that book (Java The Complete Reference Twelfth Edition)
The only way i understood the second quote, its in the code below:
interface FuncInterf<O, T>
{
int func(O op, T[] arr, T val);
}
class Operations<T>
{
int countMatches(T[] arr, T val)
{
int counter = 0;
for(int i=0; i<arr.length; i++)
if(arr[i] == val)
counter++;
return counter;
}
}
public class Main
{
static <O, T> int methRef(FuncInterf<O, T> fI, O op, T[] arr, T val)
{
return fI.func(op, arr, val);
}
public static void main(String[] args)
{
Integer[] iArr = {1, 2, 3, 4, 3, 5};
int iVal = 3;
int matches = 0;
FuncInterf<Operations<Integer>, Integer> fI = Operations<Integer>::countMatches;
matches = methRef(fI, new Operations<Integer>(), iArr, iVal);
System.out.println("Total of " + iVal + "'s: " + matches);
}
}
The interesting part is that, an extra type parameter (letter 'O'
) on interface FuncInterface <O, T>
and also, an extra parameter (O op
) on method func
is needed to be able to reference the method countMatches
and do what the book says:
In cases in which a
generic class is specified, the type argument follows the class name and precedes the ::
Which is: Operations<Integer>::countMatches;
The reason that O op
is created its because it will be the object thats going to call/reference countMatches
method from methRef
method in return fI.func(op, arr, val);
O
will be type Operations<T>
, and <T>
Integer in this example. Resulting in Operations<Integer>
This kind of method reference its a 'Reference to instance method of an arbitrary object of a given type'. The method (countMatches
) thats implementing Functional Interface's SAM (Single Abstract Method) doesn't need to have an extra parameter O op
, because actually op
its "indirectly" calling countMatches
SomeTest <Integer> mRef = MyClass :: <Integer> myGenMeth;
in that main class – Saddlery