Kinds Of Method References
In this lesson, you will be introduced to different kinds of method references and their syntaxes.
Table of Contents
Introduction
Method references are commonly used in functional programming, especially when working with streams, to specify a method that should be used as a parameter in a method call.
Method references in Java allow passing methods around as if they were values. Rather than passing a method as an object, you can use method references to pass the method itself. This can make code more concise and easier to read, especially when working with functional interfaces and lambdas.
Syntax (generic)
The generic syntax for all these method references is as follows.
ClassName/ObjectName::MethodName
What are the different kinds of method references?
In the previous lesson, you learned what method references are and how to use them. Let us take a step further and learn how to use them in different scenarios.
The four kinds of method references in Java are based on the type of method referenced and what it is called.
Here's a brief explanation of each kind:
A) Reference to static methods
A static method reference refers to a static method of a class. This is done using the class name followed by the method name, separated by a double colon ::
operator.
For example, Math::abs
refers to the static abs
method of the Math
class.
B) Reference to instance methods of particular objects
An instance method reference refers to a non-static method of an object. This is done using the object name followed by the method name, separated by the double colon ::
operator.
For example, str::length
refers to the length method of the str
object.
C) Reference to an instance method of a class
This is also called "Reference to an instance method of an arbitrary object of a particular type".
An instance method reference is also used to refer to a non-static method of a class. This is done using the class name followed by the method name, separated by a double colon ::
operator.
The method reference must be used in a context where an object of that class is provided as an argument. For example, String::compareToIgnoreCase
refers to the compareToIgnoreCase
method of the String
class.
D) Reference to a constructor.
A constructor method reference refers to a constructor of a class. This is done using the class name followed by the new keyword, separated by a double colon ::
operator.
For example, ArrayList::new
refers to the constructor of the ArrayList
class.
In the next lessons, you will learn each of them in detail.
Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.