java - Java中的 "@Override"有什么用?

标签 java syntax

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/

相关文章:

java - groovy 需要加载源文件

java - ArrayList相关调试问题

c++ - 这段代码是如何工作的?

python : 'import module' vs 'import module as'

java - 将 double 从一项 Activity 转移到另一项 Activity

java - 无法在 Java 二维数组中赋值 - ArrayIndexOutOfBoundsException

PHP:什么是 "->"和 "=>"?

powershell - "-"在 Powershell 中做什么

mysql - 我可以选择性地将数据从文本文件导入MySQL吗?

java - 从默认相机拍摄的时间戳图像