你什么时候使用Java的@Override注释?为什么? [英] When do you use Java's @Override annotation and why?

查看:110
本文介绍了你什么时候使用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注释?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆