I read the following code in "Java - The beginner's guide"
interface SomeTest <T>
{
boolean test(T n, T m);
}
class MyClass
{
static <T> boolean myGenMeth(T x, T y)
{
boolean result = false;
// ...
return result;
}
}
The following statement is valid
SomeTest <Integer> mRef = MyClass :: <Integer> myGenMeth;
Two points were made regarding the explanation of the above code
1 - When a generic method is specified as a method reference, its type argument comes after the
::
and before the method name.2 - In case in which a generic class is specified, the type argument follows the class name and precedes the
::
.
The code above is the example of the first quoted point
Can someone provide me an example of code which implement the second quoted point?
(Basically I don't understand the second quoted point).
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.
The second quoted point just means that the type parameter belongs to the class. For example:
class MyClass<T>
{
public boolean myGenMeth(T x, T y)
{
boolean result = false;
// ...
return result;
}
}
This would then be called like this:
SomeTest<Integer> mRef = new MyClass<Integer>() :: myGenMeth;
For example
Predicate<List<String>> p = List<String>::isEmpty;
Actually we don't need the type argument here; the type inference will take care of
Predicate<List<String>> p = List::isEmpty;
But in cases type inference fails, e.g. when passing this method reference to a generic method without enough constraints for inference, it might be necessary to specify the type arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With