本文翻譯自:Should we @Override an interface's method implementation?
Should a method that implements an interface method be annotated with @Override
? 是否應該使用@Override
註釋實現接口方法的方法?
The javadoc of the Override
annotation says: Override
註釋的javadoc說:
Indicates that a method declaration is intended to override a method declaration in a superclass. 指示方法聲明旨在覆蓋超類中的方法聲明。 If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message. 如果使用此批註類型註釋方法但不覆蓋超類方法,則編譯器需要生成錯誤消息。
I don't think that an interface is technically a superclass. 我不認爲接口在技術上是超類。 Or is it? 或者是嗎?
#1樓
參考:https://stackoom.com/question/tJG/我們應該-Override接口的方法實現嗎
#2樓
You should use @Override whenever possible. 你應該儘可能使用@Override。 It prevents simple mistakes from being made. 它可以防止出現簡單的錯誤。 Example: 例:
class C {
@Override
public boolean equals(SomeClass obj){
// code ...
}
}
This doesn't compile because it doesn't properly override public boolean equals(Object obj)
. 這不會編譯,因爲它沒有正確覆蓋public boolean equals(Object obj)
。
The same will go for methods that implement an interface ( 1.6 and above only ) or override a Super class's method. 對於實現接口( 僅限1.6及更高版本 )或覆蓋超類的方法的方法也是如此。
#3樓
I would use it at every opportunity. 我會抓住每個機會。 See When do you use Java's @Override annotation and why? 請參閱何時使用Java的@Override註釋以及爲什麼?
#4樓
I believe that javac behaviour has changed - with 1.5 it prohibited the annotation, with 1.6 it doesn't. 我相信javac的行爲已經改變了 - 用1.5它禁止了註釋,而1.6則沒有。 The annotation provides an extra compile-time check, so if you're using 1.6 I'd go for it. 註釋提供額外的編譯時檢查,所以如果你使用1.6,我會去做。
#5樓
Overriding your own methods inherited from your own classes will typically not break on refactorings using an ide. 覆蓋從您自己的類繼承的自己的方法通常不會使用ide在重構上中斷。 But if you override a method inherited from a library it is recommended to use it. 但是如果重寫從庫繼承的方法,建議使用它。 If you dont, you will often get no error on a later library change, but a well hidden bug. 如果你不這樣做,你通常會在以後的庫更改中沒有錯誤,但是一個隱藏得很好的錯誤。
#6樓
當您在創建實現接口的類期間告訴它“生成未實現的方法”時,Eclipse本身將添加@Override
註釋。