我们应该@Override 接口的方法实现吗? [英] Should we @Override an interface's method implementation?
问题描述
实现接口方法的方法是否应该用@Override
注解?
Should a method that implements an interface method be annotated with @Override
?
表示方法声明旨在覆盖超类中的方法声明.如果某个方法使用此注解类型进行注解但未覆盖超类方法,则编译器需要生成错误消息.
Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.
我不认为接口在技术上是超类.或者是吗?
I don't think that an interface is technically a superclass. Or is it?
推荐答案
你应该尽可能使用@Override.它可以防止出现简单的错误.示例:
You should use @Override whenever possible. It prevents simple mistakes from being made. Example:
class C {
@Override
public boolean equals(SomeClass obj){
// code ...
}
}
这不会编译,因为它没有正确覆盖 public boolean equals(Object obj)
.
This doesn't compile because it doesn't properly override public boolean equals(Object obj)
.
同样适用于实现接口(仅限 1.6 及更高版本)或覆盖超类方法的方法.
The same will go for methods that implement an interface (1.6 and above only) or override a Super class's method.
这篇关于我们应该@Override 接口的方法实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!