This question on stackoverflow has an answer that replaces calling methods using reflection with functional programming. I like it, but I don't understand why it works. The interface defines an execute method, but nothing explicitly implements that method!
Why does this work? Why does it even compile? What am I missing?
@FunctionalInterface
public interface Method {
double execute(int number);
}
public class ShapeArea {
private final static double PI = 3.14;
private Method[] methods = {
this::square,
this::circle
};
private double square(int number) {
return number * number;
}
private double circle(int number) {
return PI * number * number;
}
public double run(int methodIndex, int number) {
return methods[methodIndex].execute(aNumber);
}
}
Aucun commentaire:
Enregistrer un commentaire