So I am familiar with functional interfaces in java, and their use with lambda expressions. A functional interface can only contain one abstract method. When using this lonely method from a lambda expression, you do not need to specify its name - since there is only one abstract method in the interface, the compiler knows that's the method you are referencing.
Example:
// Functional Interface:
@FunctionalInterface
public interface Ball
{
void hit();
}
// Lambda to define, then run the hit method:
Ball b = () -> System.out.println("You hit it!");
b.hit();
Although it is obvious why a functional interface can only contain one abstract method, I do not understand why it is not possible to overload that method.
For example, the following will not compile:
// (NOT) Functional Interface:
@FunctionalInterface
public interface Ball
{
void hit();
void hit(boolean miss);
}
// Lambda to define, then run the hit method:
Ball b = () -> System.out.println("You hit it!");
Ball ba = (boolean miss) -> System.out.println(miss);
b.hit();
ba.hit(false);
The compiler states that the Ball
interface is not functional because it contains more than one method, but in this case I do not understand why this would be a problem - As long as the two methods take different parameters, it should be possible to infer which method I'm referencing in the lambda based on what parameters I define.
Can someone explain why it is not possible to overload a abstract method within a functional interface?