Java8 - Learn Method Reference Tutorials with examples


Method reference basics

java introduced method reference in java8 version. Method reference allows the developer to call a method or constructor by their names. Method references are one more short way of writing lambda expression. Method references use the symbol “::” to separate class/object/constructor from method name Sometimes we used to get the compile-time warning like “The target type of this expression must be a functional interface” so this error is because the need to assign method reference or lambda expression to functional interface

method reference syntax

Classname:: methodname  
Instancename:: methodname  
Constructorname::new  

Various types of method references introduced.

  • Static methods reference
  • Instance method reference 
  • Constructor reference 

Static method reference example

 Static methods are global to class, They can directly call using Classname.staticmethod() with java8, You can call using Classname::static-method

public class MethodReferenceExample {  
  
 public static void main(String[] args) {  
  // Using lambda expression  
  BooleanTest lambdaExample = (n) -> PositiveNumberCheck.isPositive(n);  
  System.out.println(lambdaExample.test(2));  
  System.out.println(lambdaExample.test(-2));  
  
  // Using method reference  
  BooleanTest methodRefExample = PositiveNumberCheck::isPositive;  
  System.out.println(methodRefExample.test(2));  
  System.out.println(methodRefExample.test(-2));  
 }  
}  
  
@FunctionalInterface  
interface BooleanTest {  
 boolean test(int n);  
}  
class PositiveNumberCheck {  
 public static boolean isPositive(int n) {  
  return n >= 0;  
 }  
}  

And the output of the above code execution

true  
false  
true  
false  

Instance method reference example

Instance methods work on instances of a class. Prior to java 8, we used to call instances method using new class(). method name with java8, You can call object:: instance-method

import java.util.function.Function;  
public class MethodReferenceExample {  
 public Integer IncrementByOne(Integer value) {  
  return value + 1;  
 }  
 public static void main(String[] args) {  
  Function<Integer, Integer> function = new MethodReferenceExample()::IncrementByOne;  
  System.out.println(function.apply(5));  
 }  
}  

And the output is

6  

Construction reference example 

Construction reference can be called using the new operator. Reference to construction is executing via functional interface Here is an example for construction reference

import java.util.function.Consumer;  
public class MethodReferenceExample {  
  
 public static void main(String[] args) {  
  Consumer<String> function = Emp::new;  
  function.accept("Hello");  
 }  
}  
class Emp {  
 Emp(String msg) {  
  System.out.print(msg);  
 }  
}  

And the output is

Hello  

Similar Posts