Java 中@Override 的作用是什么?
除了让编译器检查超类是否具有该方法之外,还有什么理由用 @Override
注释方法吗?
Possible Duplicate:
When do you use Java’s @Override annotation and why?
Is there any reason to annotate a method with @Override
other than to have the compiler check that the superclass has that method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如您所描述的,@Override 创建一个编译时检查来检查方法是否被覆盖。 这对于确保您在尝试覆盖时不会遇到愚蠢的签名问题非常有用。
例如,我看到以下错误:
此类按编写方式进行编译,但将 @Override 标记添加到 equals 方法将导致编译错误,因为它不会覆盖 Object 上的 equals 方法。 这是一个简单的错误,但即使是经验丰富的开发人员也可能会忽视它
As you describe, @Override creates a compile-time check that a method is being overridden. This is very useful to make sure you do not have a silly signature issue when trying to override.
For example, I have seen the following error:
This class compiles as written, but adding the @Override tag to the equals method will cause a compilation error as it does not override the equals method on Object. This is a simple error, but it can escape the eye of even a seasoned developer
它不仅让编译器进行检查——尽管这足以使其有用; 它还记录了开发人员的意图。
例如,如果您重写一个方法,但不在类型本身的任何地方使用它,稍后查看代码的人可能会想知道它到底为什么在那里。 注释解释了其目的。
It not only makes the compiler check - although that would be enough to make it useful; it also documents the developer's intention.
For instance, if you override a method but don't use it anywhere from the type itself, someone coming to the code later may wonder why on earth it's there. The annotation explains its purpose.
不,你几乎已经做到了。
@Override
告诉编译器您的意图:如果您标记一个方法@Override
,则您打算重写超类(或接口,例如Java 6)。 一个好的 IDE 将有助于标记任何覆盖没有@Override
的方法的方法,因此两者的结合将有助于确保您正在做您想要做的事情。Nope, you pretty much nailed it.
@Override
tells the compiler your intent: if you tag a method@Override
, you intended to override something from the superclass (or interface, in Java 6). A good IDE will helpfully flag any method that overrides a method without@Override
, so the combination of the two will help ensure that you're doing what you're trying to.不——除了它还提高了可读性(即,除了 IDE 使用的任何指示符之外,它还可以轻松发现方法覆盖超类中的声明)
nope -- except that it also improves readability (i.e. in addition to whatever indicator your IDE uses, it makes it easy to spot that a method overrides a declaration in the superclass)