
- Functional Programming with Java Tutorial
- Home
- Overview
- Aspects
- Functions
- Functional Composition
- Eager vs Lazy Evaluation
- Persistent Data Structure
- Recursion
- Parallelism
- Optionals & Monads
- Closure
- Currying
- Reducing
- Java 8 Onwards
- Lambda Expressions
- Default Methods
- Functional Interfaces
- Method References
- Constructor References
- Collections
- Functional Programming
- High Order Functions
- Returning a Function
- First Class Functions
- Pure Functions
- Type Inference
- Exception Handling
in Lambda Expressions - Streams
- Intermediate Methods
- Terminal methods
- Infinite Streams
- Fixed Length Streams
- Useful Resources
- Quick Guide
- Resources
- Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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