Java中的@Override是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/561365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is @Override for in Java?
提问by user65374
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?
@Override
除了让编译器检查超类是否具有该方法之外,是否有任何理由来注释方法?
采纳答案by Rob Di Marco
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.
正如您所描述的,@Override 创建一个编译时检查方法是否被覆盖。这对于确保在尝试覆盖时没有愚蠢的签名问题非常有用。
For example, I have seen the following error:
例如,我看到了以下错误:
public class Foo {
private String id;
public boolean equals(Foo f) { return id.equals(f.id);}
}
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
此类按编写的方式编译,但是将@Override 标记添加到equals 方法将导致编译错误,因为它不会覆盖Object 上的equals 方法。这是一个简单的错误,但即使是经验丰富的开发人员也能逃脱
回答by Jon Skeet
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.
例如,如果您覆盖了一个方法,但不在类型本身的任何地方使用它,稍后访问代码的人可能会想知道为什么它在那里。注释解释了它的目的。
回答by Rahel Lüthy
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)
不——除了它还提高了可读性(即,除了您的 IDE 使用的任何指示符之外,它还可以很容易地发现方法覆盖了超类中的声明)
回答by Michael Myers
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.
@Override
告诉编译器您的意图:如果您标记方法@Override
,则您打算覆盖超类(或接口,在 Java 6 中)中的某些内容。一个好的 IDE 将有助于标记任何覆盖没有 的方法的方法@Override
,因此两者的组合将有助于确保您正在做您想做的事情。