I can't figure out a use case for being able to annotate interfaces in Java.
Maybe someone could give me an example?
Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces. The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.
No we are following the dynamic binding and creating the object of interface but implementation is on the run time. So @autowired is the one that will create the object internally and we have @component for bubbleSortAlgo and the only candidate for the injection, so it will get reference from there.
The annotation can be overridden in case the child class has the annotation. Because there is no multiple inheritance in Java, annotations on interfaces cannot be inherited.
Annotations are like meta-tags that you can add to the code and apply to package declarations, type declarations, constructors, methods, fields, parameters, and variables.
I've used it in Spring to annotate interfaces where the annotation should apply to all subclasses. For example, say you have a Service interface and you might have multiple implementations of the interface but you want a security annotation to apply regardless of the annotation. In that case, it makes the most sense to annotate the interface.
A use case that I am working with is javax/hibernate bean validation, we are using interfaces to help us on avoiding to define validations on every specific class.
public interface IUser {
@NotNull Long getUserId();
...
}
public class WebUser implements IUser {
private Long userId;
@Override
public Long getUserId(){
return userId;
}
...
}
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