Java Course
- Functional Interface method can be mapped to our specified method by using :: (double colon) operator. This is called method reference.
- Our specified method can be either static method or instance method.
- Functional Interface method and our specified method should have same argument types, except this the remaining things like returntype, methodname, modifiersetc are not required to match.
Syntax:
if our specified method is static method, Classname::methodName
if the method is instance method, Objref::methodName
Functional Interface can refer lambda expression and Functional Interface can also refer method reference. Hence lambda expression can be replaced with method reference. Hence method reference is alternative syntax to lambda expression.
Let's see an example,
@FunctionalInterface interface MethodReference { void display(); } public class StaticMethodReferenceDemo { static void display() { System.out.println("display"); } public static void main(String args[]) { /* With Methodreference */ MethodReference methodReference = StaticMethodReferenceDemo::display; methodReference.display(); /* With Lambda */ MethodReference methodReferenceLambda = () -> StaticMethodReferenceDemo.display(); methodReferenceLambda.display(); } }
Rule1: Method names can be different.
Rule2: Parameter should be same in both methods.
Rule3: Method reference can be used in functional interface only.
Rule4: Return type of both methods doesn't need to match exactly - it just needs to be assignment-compatible with (or a subtype of) the functional interface method's return type, or the interface method can be void to ignore the return value entirely.
We can say MethodReference is alternative syntax for Lambda Expression.
@FunctionalInterface interface MethodReferenceNS { void display(); } public class NonStaticMethodReferenceDemo { void display() { System.out.println("display"); } public static void main(String args[]) { NonStaticMethodReferenceDemo obj = new NonStaticMethodReferenceDemo(); /* With Methodreference */ MethodReferenceNS methodReference = obj::display; methodReference.display(); /* With Lambda */ MethodReferenceNS methodReferenceLambda = () -> obj.display(); methodReferenceLambda.display(); } }
For non-static method reference we just need to create an object and call the method where as for static method reference you can use Class Name directly.
We can use :: ( double colon )operator to refer constructors also.
Syntax: classname :: new