Joseph Haugh
University of New Mexico











public class Duck {
protected QuackBehavior quackBehavior;
// ... more
public void doQuack() {
quackBehavior.quack();
}
}
public class MallardDuck extends Duck {
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
public void display() {
System.out.println("I’m a real Mallard duck!");
}
}
public void setFlyBehavior(FlyBehavior fb){
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb){
quackBehavior = qb;
}
Recall, that a lambda is a function without a name
For example, we could implement a function to add 1 to its argument and return the result like this:
int add1(int n) {
return n + 1;
}We could also do this using a lambda like this:
x -> x + 1This is often desirable for smaller functions
We can write a function which takes another function as an argument as follows:
public static int foo(Function<Integer, Integer> f, Integer x) {
return f.apply(x);
}This is called a higher order function
Since this uses generics, the types must be reference types
public class Main {
public static int add1(int n) {
return n + 1;
}
public static int foo(Function<Integer, Integer> f, Integer x) {
return f.apply(x);
}
public static void main() {
System.out.println(foo(x -> x + 1, 2)); // Lambda way
System.out.println(foo(Main::add1, 2)); // Method reference
}
}
When you have an interface with one function such as:
public interface FlyBehavior {
void fly();
}It is can be useful to use the @FunctionalInterface annotation
The annotation only enforces that the interface can only have 1 function
Such an interface can be implement with a lambda or method reference
Given the FlyBehavior interface:
public interface FlyBehavior {
void fly();
}We could implement in 1 or three ways:
With a class:
public class FlyWithWings implements FlyBehavior {
@Override
public void fly() {
System.out.println("Winged Flying");
}
}Given the FlyBehavior interface:
public interface FlyBehavior {
void fly();
}We could implement in 1 or three ways:
With a lambda:
FlyBehavior flyBehavior = () -> System.out.println("Winged Flying");Given the FlyBehavior interface:
public interface FlyBehavior {
void fly();
}We could implement in 1 or three ways:
With a method reference:
public class Main {
public static void fly() {
System.out.println("Winged Flying");
}
public static void main() {
FlyBehavior flyBehavior = Main::fly;
}
}