2016-01-25 18:05:55 -08:00
|
|
|
// generics/DogsAndRobotMethodReferences.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2016-01-25 18:05:55 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// "Assisted Latent Typing"
|
|
|
|
import typeinfo.pets.*;
|
|
|
|
import java.util.function.*;
|
|
|
|
|
2016-11-21 12:37:57 -08:00
|
|
|
class PerformingDogA extends Dog {
|
2016-01-25 18:05:55 -08:00
|
|
|
public void speak() { System.out.println("Woof!"); }
|
|
|
|
public void sit() { System.out.println("Sitting"); }
|
|
|
|
public void reproduce() {}
|
|
|
|
}
|
|
|
|
|
2016-11-21 12:37:57 -08:00
|
|
|
class RobotA {
|
2016-01-25 18:05:55 -08:00
|
|
|
public void speak() { System.out.println("Click!"); }
|
|
|
|
public void sit() { System.out.println("Clank!"); }
|
|
|
|
public void oilChange() {}
|
|
|
|
}
|
|
|
|
|
2016-11-21 12:37:57 -08:00
|
|
|
class CommunicateA {
|
2016-01-25 18:05:55 -08:00
|
|
|
public static <P> void perform(P performer,
|
|
|
|
Consumer<P> action1, Consumer<P> action2) {
|
|
|
|
action1.accept(performer);
|
|
|
|
action2.accept(performer);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class DogsAndRobotMethodReferences {
|
|
|
|
public static void main(String[] args) {
|
2016-11-21 12:37:57 -08:00
|
|
|
CommunicateA.perform(new PerformingDogA(),
|
|
|
|
PerformingDogA::speak, PerformingDogA::sit);
|
|
|
|
CommunicateA.perform(new RobotA(),
|
|
|
|
RobotA::speak, RobotA::sit);
|
|
|
|
CommunicateA.perform(new Mime(),
|
2017-05-10 11:45:39 -06:00
|
|
|
Mime::walkAgainstTheWind,
|
|
|
|
Mime::pushInvisibleWalls);
|
2016-01-25 18:05:55 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
|
|
|
Woof!
|
|
|
|
Sitting
|
|
|
|
Click!
|
|
|
|
Clank!
|
|
|
|
*/
|