Is below interface a valid functional interface in Java 8?
@FunctionalInterface
interface Normal{
public abstract String move();
public abstract String toString() ;
}
Why doesn't it give me a compile time error?
An Interface that contains exactly one abstract method is known as functional interface. It can have any number of default, static methods but can contain only one abstract method. It can also declare methods of object class.
Functional interface can have only one abstract method. It can contain multiple default and static methods.
Important : The functional interface also known as Single Abstract Method Interface was introduced to facilitate Lambda functions. Since a lambda function can only provide the implementation for 1 method it is mandatory for the functional interface to have ONLY one abstract method.
Conceptually, a functional interface has exactly one abstract method.
What Alok quoted is true, but he overlooked something, which makes his final answer (that the code is invalid) wrong:
The interface has one method String toString()
which every class already implements, inheriting it from Object
. I.e. the declared interface method already has an implementation, similar to a default method. Hence, there is no compile error and Normal
can be used as a functional interface as shown in my MCVE:
package de.scrum_master.stackoverflow;
@FunctionalInterface
interface Normal {
String move();
String toString();
}
BTW, no need to declare interface methods as public
because they always are. Same goes for abstract
.
package de.scrum_master.stackoverflow;
public class NormalApp {
static void doSomething(Normal normal) {
System.out.println(normal.move());
System.out.println(normal.toString());
}
public static void main(String[] args) {
doSomething(() -> "xxx");
}
}
If you run the driver application, you will see this console log:
xxx
de.scrum_master.stackoverflow.NormalApp$$Lambda$1/1530388690@28c97a5
Now if you change the method name toString
to something else, e.g. toStringX
, you will see that due to the @FunctionalInterface
there is the expected error message when compiling the class:
Unexpected @FunctionalInterface annotation
de.scrum_master.stackoverflow.Normal is not a functional interface
multiple non-overriding abstract methods found in interface de.scrum_master.stackoverflow.Normal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With