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
是否真的有一些功能,或者它只是一种评论?
最佳答案
来自 annotations 上的 Java 教程:
@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() { }
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 Override .假设您想覆盖一个方法,equals
在这种情况下,但您写道:
public boolean equals(Foo that) { ... }
代替:
public boolean equals(Object that) { ... }
虽然此代码是合法的,但使用 @Override
注释 equals
方法声明会触发编译时错误,因为您实际上并没有覆盖它,您重载它。这可能会导致严重的错误,而 Override
注释类型有助于及早检测到它们。
关于java - Java中的 "@Override"有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2489974/