什么是“@ Override”在java中? [英] What's "@Override" there for in java?
问题描述
public class Animal {
public void eat() { System.out.println("I eat like a generic Animal."); }
}
public class Wolf extends Animal {
@Override
public void eat() { System.out.println("I eat like a wolf!"); }
}
@Override
实际上有一些功能,或者它只是有点评论?
Does @Override
actually have some functionality or it's just kinda comment?
推荐答案
来自Java教程注释:
@Override
-@Override
注释
通知编译器元素
是意味着覆盖在超类中声明的元素
(覆盖
方法将在名为接口和
继承的
课程中讨论。)
@Override
— the@Override
annotation informs the compiler that the element is meant to override an element declared in a superclass (overriding methods will be discussed in the the lesson titled "Interfaces and Inheritance").
// mark method as a superclass method
// that has been overridden
@Override
int overriddenMethod() { }
虽然不需要使用t重写方法时,他的
注释,
有助于防止错误。如果标有 @Override
的
方法无法正确覆盖
其超类之一的方法,则编译器
生成错误。
While it's not required to use this
annotation when overriding a method,
it helps to prevent errors. If a
method marked with @Override
fails to
correctly override a method in one of
its superclasses, the compiler
generates an error.
让我们看一下Java语言规范中给出的示例, 9.6.1.4覆盖。假设你要覆盖一个方法,等于
,但是你写道:
Let's take a look at the example given in the Java Language specifications, 9.6.1.4 Override. Let's say you want to override a method, equals
in that case, but you wrote:
public boolean equals(Foo that) { ... }
而不是:
public boolean equals(Object that) { ... }
虽然此代码合法,但使用 @Override $注释
等于
方法声明c $ c>会触发编译时错误,因为你实际上没有覆盖它,你正在重载它。这可能会导致令人讨厌的错误,覆盖
注释类型有助于及早发现它们。
While this code is legal, annotating the equals
method declaration with @Override
would trigger a compile time error because you're in fact not overriding it, you're overloading it. This can cause nasty bugs and the Override
annotation type helps at detecting them early.
这篇关于什么是“@ Override”在java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!