@Override注解

首先来看码:

 1 /**
 2  * Indicates that a method declaration is intended to override a
 3  * method declaration in a supertype. If a method is annotated with
 4  * this annotation type compilers are required to generate an error
 5  * message unless at least one of the following conditions hold:
 6  *
 7  * <ul><li>
 8  * The method does override or implement a method declared in a
 9  * supertype.
10  * </li><li>
11  * The method has a signature that is override-equivalent to that of
12  * any public method declared in {@linkplain Object}.
13  * </li></ul>
14  *
15  * @author  Peter von der Ah&eacute;
16  * @author  Joshua Bloch
17  * @jls 9.6.1.4 @Override
18  * @since 1.5
19  */
20 @Target(ElementType.METHOD)
21 @Retention(RetentionPolicy.SOURCE)
22 public @interface Override {
23 }

源码中注释翻译如下:

  指示方法声明旨在覆盖超类型中的方法声明。如果用这种注释类型的编译器对方法进行注释,则需要生成错误消息,除非至少满足下列条件之一:

  •   该方法确实覆盖或实现在超类型中声明的方法。
  •   该方法的签名与在对象中声明的任何公共方法的签名是等效的。

(以上翻译来自有道)

简单来说来说就是:加了此注解的方法,表示此方法是一个覆写的方法,如果不满足覆写会报错。

idea报错如下:

总结@Override注解作用:

  • 检测方法覆写的正确性。
  • 告诉读者此方法是覆写方法。
原文地址:https://www.cnblogs.com/Y-zhiwei/p/10026645.html