what is method reference in java code example
Example 1: java method
public class Main {
public static void main(String args[]) {
SayHi();
int sum = AddNums(5, 6);
System.out.println(sum);
}
public static void SayHi() {
System.out.println("Hi!");
}
public static int AddNums(int a, int b) {
return a + b;
}
Example 2: java method reference
Java provides a feature called method
reference in Java 8. Method reference
is used to refer method of functional interface.
It is compact and easy form
of lambda expression. Each time when
you are using lambda expression to just
referring a method, you can replace your
lambda expression with method reference.
Types of Method References:
- Reference to a static method. Syntax ==> ContainingClass::staticMethodName
- Reference to an instance method. Syntax ==> containingObject::instanceMethodName
- Reference to a constructor. Syntax ==> ClassName::new
Example 3: method in java
Method is a collection of statements
which returns a value upon its execution
Method have a return and the method's name may or not be same as the class
name.
Method is invoked explicitly.
Method is not provided by compiler in any case.
Methods are inherited by child classes.
Example 4: what are method in java
Static methods: A static method is a method that can be called and executed without creating an object
Instance methods: These methods act upon the instance variables of a class
Factory methods: A factory method is a method that returns an object to the class to which it belong