Java Reference
In-Depth Information
How It Works
Lambda expressions allow you to encapsulate functionality and assign to a variable for
later use, if desired. Believe it or not, there is a simplified variation of a lambda expres-
sion referred to as a method reference. If a class contains a method that is derived from
the implementation of a functional interface, then that method can be obtained or “cap-
tured” and assigned to a variable for later use. The concept being that the method con-
tains functionality that can be assigned to a variable of the same type as the functional
interface.
In the example for this recipe, a functional interface identified as
Volume
contains
a single abstract method,
calculateVolume()
. The
PoolCalculator
class im-
plements the
Volume
interface, as it contains an implementation of the
calcu-
lateVolume()
method. To capture this method via a method reference, you can use
the following syntax on an instance of the
PoolCalculator
class:
poolCalculator::calculateVolume
The double colon operator is used to indicate a method reference. In this example, a
reference to an instance method of a specific object is used. However there are various
types of method references; to learn more about them refer to
Chapter 6
.
2-3. Providing a Default Method Imple-
mentation in an Interface
Problem
You want to add a new method to an existing interface without breaking backward
compatibility with other code.
Solution
Develop a default method (a.k.a.
defender
method) within the interface so that any
classes implementing the interface are not required to provide an implementation of the
new method. To do so, add the new default keyword to the interface declaration and