Functional Programming - Method References



Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods −

  • Static methods - static method can be reference using ClassName::Method name notation.

//Method Reference - Static way
Factory vehicle_factory_static = VehicleFactory::prepareVehicleInStaticMode;        
  • Instance methods - instance method can be reference using Object::Method name notation.

//Method Reference - Instance way
Factory vehicle_factory_instance = new VehicleFactory()::prepareVehicle;         

Following example shows how Method references works in Java 8 onwards.

interface Factory {
   Vehicle prepare(String make, String model, int year);
}

class Vehicle {
   private String make;
   private String model;
   private int year;

   Vehicle(String make, String model, int year){
      this.make = make;
      this.model = model;
      this.year = year;
   }

   public String toString(){
      return "Vehicle[" + make +", " + model + ", " + year+ "]";
   }    
}

class VehicleFactory {
   static Vehicle prepareVehicleInStaticMode(String make, String model, int year){
      return new Vehicle(make, model, year);
   }

   Vehicle prepareVehicle(String make, String model, int year){
      return new Vehicle(make, model, year);
   }
}

public class FunctionTester {    
   public static void main(String[] args) {               
      //Method Reference - Static way
      Factory vehicle_factory_static = VehicleFactory::prepareVehicleInStaticMode;        
      Vehicle carHyundai = vehicle_factory_static.prepare("Hyundai", "Verna", 2018);
      System.out.println(carHyundai);

      //Method Reference - Instance way
      Factory vehicle_factory_instance = new VehicleFactory()::prepareVehicle;        
      Vehicle carTata = vehicle_factory_instance.prepare("Tata", "Harrier", 2019);
      System.out.println(carTata); 
   } 
}

Output

Vehicle[Hyundai, Verna, 2018]
Vehicle[Tata, Harrier, 2019]
Advertisements