Java Reference
In-Depth Information
As the last example in this category, you will use the method reference Person::getFirstName that is an instance
method reference on an unbound receiver, as shown:
List<Person> personList = Person.getPersons();
// Maps each Person object to its first name
List<String> firstNameList = FunctionUtil.map(personList, Person::getFirstName );
// Prints the first name list
FunctionUtil.forEach(firstNameList, System.out::println );
John
Wally
Donna
Supertype Instance Method References
The keyword super is used as a qualifier to invoke the overridden method in a class or an interface. The keyword
is available only in an instance context. Use the following syntax to construct a method reference that refers to the
instance method in the supertype and the method that's invoked on the current instance:
TypeName.super::instanceMethod
Consider the Priced interface and the Item class in Listing 5-15 and Listing 5-16. The Priced interface contains a
default method that returns 1.0. The Item class implements the Priced interface. It overrides the toString() method
of the Object class and the getPrice() method of the Priced interface. I have added three constructors to the Item
class that display a message on the standard output. I will use them in examples in the next section.
Listing 5-15. A Priced Interface with a Default Method of getPrice()
// Priced.java
package com.jdojo.lambda;
public interface Priced {
default double getPrice() {
return 1.0;
}
}
Listing 5-16. An Item Class That Implements the Priced Interface
// Item.java
package com.jdojo.lambda;
import java.util.function.Supplier;
public class Item implements Priced {
private String name = "Unknown";
private double price = 0.0;
 
Search WWH ::




Custom Search