Hi everyone.
Welcome back to this tutorial.
In this tutorial we'll talk about method reference.
We will be discussing the theory part as part of this tutorial.
This concept got introduced as part of Java eight.
The sole purpose of method reference is to simplify the implementation of functional interfaces.
You might be wondering, we already did that by using lambdas.
Lambdas helped us to move away from creating anonymous inner classes.
Yes, you are right, but this one is going to simplify the lambda expression itself.
And also call method reference as a shortcut for the lambda expressions from the name itself.
It is clear that this one is used to refer a method in a class.
Let's take a look at the syntax of the method reference.
The syntax is class.
Name a double colon operator followed by the method name.
The right hand side references to the method name and the left hand side references to the class name.
Let's talk about the different options that are presented here.
First example is a class name followed by the instance method name.
The second example is a class name, followed by the static method name in that class.
And then the third example is an instance of the class, followed by the method name.
Let's take a look at some of the examples where the method reference is applicable.
Metal reference can be used wherever the lambda expression is referring to the method directly.
Let's take a look at one of the example.
This is one of the example which we coded in our prior tutorials.
Here what happens is we are taking an input as a string and then we are applying the to uppercase on
top of it.
Basically, this is a function functional interface implementation.
The input is a string and output is a string.
How can we rewrite this using the method reference?
Take a look at the method reference implementation.
We give the class name as if you remember the syntax.
The syntax is class name double colon operator.
Followed by that we provide the method name.
So the syntax is going to be the string, which is a class name and followed by the double colon and
then the two uppercase method, because that's what we are trying to achieve as part of this lambda
expression.
So using method reference, we can write simpler and more readable code.
Let's take a look at some of the examples where the method reference is not applicable.
Take a look at an example.
We take a look at this example here.
We wrote our own logic.
We are not referencing to any method that is implementing this predicate functional interface.
In these kind of use cases, it is difficult to write a method reference for this one, but there is
a workaround in solving these kind of problems and writing a method reference for these kind of codes
too.
We will get into those kind of examples and we will implement those in our next tutorial.
But now this is all about method reference.
With this we came to the end of this tutorial.
Thank you for watching.