Java Reference
In-Depth Information
// Uses all method references and prints the results
System.out.println("this::toString: " + s1.get());
System.out.println("Item.super::toString: " + s2.get());
System.out.println("this::getPrice: " + s3.get());
System.out.println("Priced.super::getPrice: " + s4.get());
}
}
The test() method in the Item class uses four method references with a bound receiver. The receiver is the Item
object on which the test() method is called.
The method reference
this::toString refers to the toString() method of the Item class.
The method reference
Item.super::toString refers to the toString() method of the Object
class, which is the superclass of the Item class.
The method reference
this::getPrice refers to the getPrice() method of the Item class.
Priced.super::getPrice refers to the getPrice() method of the
Priced interface, which is the superinterface of the Item class.
The program in Listing 5-17 creates an object of the Item class and calls its test() method. The output shows the
method being used by the four method references.
The method reference
Listing 5-17. Testing the Item Class
// ItemTest.java
package com.jdojo.lambda;
public class ItemTest {
public static void main(String[] args) {
Item apple = new Item("Apple", 0.75);
apple.test();
}
}
Constructor Item(String, double) called.
this::toString: name = Apple, price = 0.75
Item.super::toString: com.jdojo.lambda.Item@24d46ca6
this::getPrice: 0.75
Priced.super::getPrice: 1.0
Constructor References
Sometimes the body of a lambda expression may be just an object creation expression. Consider the following two
statements that use a String object creation expression as the body for lambda expressions:
Supplier<String> func1 = () -> new String() ;
Function<String,String> func2 = str -> new String(str);
 
Search WWH ::




Custom Search