Engineering Full Stack Apps with Java and JavaScript
Method references or constructor references can be used to refer to an existing method or constructor by name. Classes containing these methods can be regular classes without the need to implement or extend anything. However, the target type needs to be a functional interface, as the signature of the method is infered from the functional interface's abstract method.
Target type is the type to which it is assigned through an equal operator (=) or the type of a method parameter to which it is passes to. Without a target type Java will not be able to infer the type of the method or constructor reference. This also means that there should be one functional interface per method or constructor.
Method references or constructor references are not invoked when they are assigned to a target type. They need to be invoked later using the reference type.
You can use method references on :
Static methods of any class
Instance methods of a particular object
Instance methods of an arbitrary object
References to constructor methods (constructor references)
Example: static method reference
Class Employee{
public static int compareAge( Employee e1, Employee e2)
{
// compare e1 and e2 and return return an integer
// according to the contract of compare method of comparator.
}
We can now use this static method as:
Collections.sort(empList, Employee :: compareAges);
Sort method is expecting an instance of the comparator interface. Comparator interface has a single abstract method that accept two values and returning a data type that can be used by the sort method. We are also passing a method that accept two values and return a datatype that can be used for sorting.
Example: Instance method reference
We can refer to an instance method in same class as:
Collections.sort (empList,this::compareAges);
There should be one functional interface per constructor.
Constructor references provide a means to give a different name to different constructors within a class. Otherwise they all will be having the same name as that of the class.
Give examples for:
Refering to an instance method of another object.
Constructor reference.