Is the purpose of abstract
keyword in a FunctionalInterface
to distinguish the 'lambda' method from other abstract methods?
Since methods that have no body in an interface are abstract, and Functional Interfaces that have only one method do not have the abstract keyword, I was wondering whether the real purpose of the abstract keyword is to mark or distinguish which among the 'abstract' methods in a Functional Interface will serve as the 'carrier' of the lambda expression. Is my understanding correct?
This method does not have the abstract
keyword but is a functional interface:
public interface AllTrades {
public boolean checkSalary(ATrade t);
}
now suppose the interface above had 2 methods, they are both abstract,
but the interface is no longer a FunctionalInterface
public interface AllTrades {
public boolean checkSalary(ATrade t);
public boolean checkSalary2(ATrade t);
}
Now if we mark which method is abstract, it is still not a Functional Interface
, as the answers below point out:
public interface AllTrades {
abstract public boolean checkSalary(ATrade t);
public boolean checkSalary2(ATrade t);
}
Shouldn't Java allow us to use the abstract
keyword to mark exactly one method to use as the lambda expression carrier?
That way, even though more than one abstract method exists in an interface, the one that is marked, will be chosen for routing of lambda expressions.
CodePudding user response:
Although you can use abstract
in an interface, it has no extra meaning, as all methods in an interface (except default, private or static methods) are by definition abstract. It has no extra meaning in a functional interface, and if you annotate your interface with @FunctionalInterface
, both of your examples with two methods will fail to compile as they are equivalent.
To be complete, your first example does have an abstract method, and is a potential function interface. Your second and third example both have two abstract methods, and cannot be used as a function interface.
See also the Java Language Specification 17, section 9.4:
An interface method lacking a
private
,default
, orstatic
modifier is implicitlyabstract
. Its body is represented by a semicolon, not a block. It is permitted, but discouraged as a matter of style, to redundantly specify theabstract
modifier for such a method declaration.
(emphasis mine)
and section 9.8:
A functional interface is an interface that is not declared
sealed
and has just oneabstract
method (aside from the methods ofObject
), and thus represents a single function contract.
CodePudding user response:
All methods in interfaces are public
and abstract
by default, and the inclusion of either of those modifiers does not change the behavior of the code in any way. You can verify this by compiling the second and third code samples with the @FunctionalInterface
annotation, which would result in a compile time error.
Edit: From the Java Language Specification