Greetings!
In Java we have object references. We pass objects around. What if we can pass reference to a method?
In Java 8 if we are executing only one method we can do this using lambda expressions.
For an example these are equal.
As you can see, :: separates the name of the method from the class/ object. There are 3 ways we can use method references.
Third case is different. First parameter becomes the target object of the method and rest become the parameters. For example,
We can use this and super also the same way;
In Java we have object references. We pass objects around. What if we can pass reference to a method?
In Java 8 if we are executing only one method we can do this using lambda expressions.
For an example these are equal.
(x) -> System.out.print(x)
System.out::print
As you can see, :: separates the name of the method from the class/ object. There are 3 ways we can use method references.
- object::method - object.method(parameters)
- Class::staticMethod - Class.staticMethod(parameters)
- Class::instanceMethod - firstParameter.method(parameters)
(x, y) -> Math.pow(x, y)
Math::pow
Third case is different. First parameter becomes the target object of the method and rest become the parameters. For example,
// (object, arguments) -> object.method(arguments)
name -> name.toUpperCase()
String::toUpperCase
We can use this and super also the same way;
this::instanceMethod
super::instanceMethod
inner class => lambda expression => method reference
Comments
Post a Comment