When do you use Java#39;s @Override annotation and why?(你什么时候使用 Java 的 @Override 注解,为什么?)
问题描述
使用 Java 的 @Override
注释的最佳实践是什么?为什么?
What are the best practices for using Java's @Override
annotation and why?
用 @Override
注释标记每个被覆盖的方法似乎有点过头了.是否有某些编程情况需要使用 @Override
和其他不应该使用 @Override
的情况?
It seems like it would be overkill to mark every single overridden method with the @Override
annotation. Are there certain programming situations that call for using the @Override
and others that should never use the @Override
?
推荐答案
每次重写方法时使用它有两个好处.这样做是为了您可以利用编译器检查来确保您实际上正在覆盖您认为的方法.这样,如果您犯了拼写错误的方法名称或未正确匹配参数的常见错误,您将被警告您的方法实际上并没有像您认为的那样覆盖.其次,它使您的代码更容易理解,因为当方法被覆盖时更明显.
Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.
此外,在 Java 1.6 中,您可以使用它来标记方法何时实现接口以获得相同的好处.我认为最好有一个单独的注解(如 @Implements
),但总比没有好.
Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements
), but it's better than nothing.
这篇关于你什么时候使用 Java 的 @Override 注解,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你什么时候使用 Java 的 @Override 注解,为什么?


基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01