標籤:override
@Override註解是作用於原始碼的註解,用於表明註解的方法重寫了父類型的方法,但是這個註解在1.5和1.6及以後是有區別的。1.5中,只能用於在繼承某個類時,重寫父類中的方法,而在實現一個介面中的方法時,是不能使用該註解的,從1.6開始,才支援實現父介面的方法使用該註解。但是在@Override原始碼文檔中,1.6沒有對這個變化進行說明,到1.7才進行了說明。
下面是1.5和1.6的源碼:
package java.lang;import java.lang.annotation.*;/** * 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. * * @author Joshua Bloch * @since 1.5 */@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override {}意思是:表示一個方法聲明打算重寫超類中的某個方法聲明。如果方法利用此註解類型進行註解但沒有重寫超類方法,則編譯器會產生一條錯誤訊息。
下面是1.7的源碼:
package java.lang;import java.lang.annotation.*;/** * Indicates that a method declaration is intended to override a * method declaration in a supertype. If a method is annotated with * this annotation type compilers are required to generate an error * message unless at least one of the following conditions hold: * * <ul><li> * The method does override or implement a method declared in a * supertype. * </li><li> * The method has a signature that is override-equivalent to that of * any public method declared in {@linkplain Object}. * </li></ul> * * @author Peter von der Ahé * @author Joshua Bloch * @jls 9.6.1.4 Override * @since 1.5 */@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override {}意思是:表示一個方法聲明打算重寫父類型中的某個方法聲明。如果方法利用此註解類型進行註解時,編譯器必鬚生成一條錯誤訊息,除非滿足下列兩個條件之一:
- 該方法重寫或實現了父類型中聲明的某個方法
- 該方法的簽名與Object類中聲明的某個公用方法重寫等價(override-equivalent)的
關於重寫等價的意思可以查看http://stackoverflow.com/questions/16207386/what-is-override-equivalence-and-how-is-it-related-to-override
可以注意到兩個詞的變化:
Indicates that a method declaration is intended to override a method declaration in a superclass.
Indicates that a method declaration is intended to override a method declaration in a supertype.
那就是1.5中是superclass,則1.7中是supertype。一個是父類,一個是父類型。為什麼1.6的文檔沒有對此變化進行修改,但實質上卻支援實現介面的方法可以使用@Override,無從知曉,可能是沒有及時的更新文檔吧。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
關於@Override在1.5和1.6之後的區別