6
Starting from java 8, for an interface to become functional, it needs to have only one right method ? However we have the @Functionface annotation, which explicitly defines that this interface is functional.
But what is the main difference in using or not this annotation, if with only one method it already becomes functional ?
@FunctionalInterface
public interface FuncionalInterface <T>{
boolean valida(T t);
}
public interface FuncionalInterface <T>{
boolean valida(T t);
}
When printing the result is the same either with the annotation or without, see in main:
public static void main(String[] args) {
FuncionalInterface<String> funcionalInterface = valor -> valor.matches("[0-9]{5}-[0-9]{3}");
System.out.println(funcionalInterface.valida("45680-000"));
}
I did the test I added one more method, and the IDE error, in case you now understand the annotation prevent that if someone else picks up your code, and have a functional interface, do not add more methods to it, example if an interface is functional without the annotation, another programmer can try to make it generic, example you have an interface to a DAO if there is no note on it signaling look I am a functional interface, another guy may think I have an interface with only one method I will take this shit a Daogenerico, get it? In the case functional interface can only have default methods?
– HashMap
@Hashmap I don’t know if I understood your doubt of the last comment. Unfortunately you can’t prevent someone from using any interface as functional. However, when you create classes and interfaces, call it the API, you establish a contract with whom you will use them and it is up to whom you will use to obey the contract. If a class does not have the annotation and then the code of the person breaks because another method has been added, it is her fault for not obeying the contract, so she needs to change the code. About the default method I don’t understand. You’re talking about implementing methods on interfaces?
– utluiz
Now I understood that confusing things was worth , orbigado by the answer.
– HashMap