For instance I have this Interface:
package tester;
public interface Calculator{
public int calculate(int a,int b);
}
or
package tester;
@FunctionalInterface
public interface Calculator{
public int calculate(int a,int b);
}
I can treat the first one as a functional interface too. For example :
package tester;
public class A {
int a;
int b;
int sum;
A(Calculator c,int e, int d){
a=e;
b=d;
sum =c.calculate(a, b);
}
int get(){
return sum;
}
}
The class runner
package tester;
public class runner {
public static void main(String a[]){
System.out.println(new A((x,b)-> (x+b),1,2).get());
}
}
The code works with or without the annotations, then why annotations? Why can't it be said that any interface with a single method can be a functional interface?
Yes any interface with one abstract method to implement can be a functional interface, the annotation FunctionalInterface
is not required, it is only an informative annotation as stated into the javadoc.
An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.
...
However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a
FunctionalInterface
annotation is present on the interface declaration.