問題描述
使用 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 注解,為什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!