Or in particular: What is the difference between
interface A {
void fa();
}
interface B extends A {
void fa();
void fb();
}
and
interface A {
void fa();
}
interface B extends A {
@Override
void fa();
void fb();
}
Does it effect the implementing class in any way?
CodePudding user response:
No it should not. The class that implements interface B
will still have to provide an implementation of void fa();
regardless whether interface B annotates the same method signature with @Override
or not. Also, putting the @Override
annotation in interface B doesn't make a lot of sense in this case because the annotation basically means that you are overriding the implementation that the super class gave to that method signature. Since Interface A
nor Interface B
provides an implementation to void fa()
it doesen't make sense.
It would make sense if interface A
provided a default implementation to void fa()
For example:
interface A {
public default void fa(){
System.out.println("My default implementation");
}
}
In this case Interface B would be overriding the implementation given to fa()
from Interface A by making it abstract again. The same goes when Interface A defines fa()
as abstract and Interface B gives it an implementation by turning it into a default
method.
CodePudding user response:
The @Override annotation is just a reminder to the compiler to show you an error if you define something wrong. It doesn't affect anything. The good practise is to write it always.
CodePudding user response:
Adding or omitting @Override
doesn't change the overriding behaviour of the fa
method. It's an override based on the name and parameter types (in this case none), nothing else. The return type needs to be compatible (covariant return), but is not part of the "is this an override or not" decision.
The @Override
annotation is (mostly) used to verify that a method is overriding a method from a super type. If you omit it, there may be a warning from your IDE or other tooling like SonarQube, but the compiler doesn't care. If you add it incorrectly, that's when its true purpose kicks in - you'll get a compiler error.