【Java學習筆記】10:三種系統內建的Annotation
Annotation是Java的一種特殊的註釋語法。
內建的三個Annotation:
@Override、@Deprecated、@SuppressWarnings
@Override表示進行正確的覆寫操作
package day10; class Person { public String say() { return "人在說話"; } } class Student extends Person { @Override public String say() { return "學生在說話"; } } public class OverDemo { public static void main(String[] args) { Person a = new Student(); System.out.println(a.say()); } }
執行結果:學生在說話
Student類繼承了Person類,並且覆寫了其中的say()方法,如果在Person類中@Override下覆寫的say()方法名稱編寫錯誤了,就肯定不是覆寫了。這時如果沒有@Override編譯器仍然不會報錯,當用Person去建立Student物件時呼叫的就只能是Person中的say()方法了。
@Deprecated表示不建議使用的操作
package day10; class Info { @Deprecated public String getInfo() { return "Hello"; } } public class TestInfo { public static void main(String[] args) { System.out.println(new Info().getInfo()); } }
不使用@Deprecated時:
使用@Deprecated時:
執行結果:Hello
使用@Deprecated宣告只是不建議使用,如果使用的話,只是會出現警告而已。例如執行緒中的stop()、resume()、suspend()等方法是不建議使用的。
@SuppressWarnings表示壓制警告。如果有一些警告資訊,用它可以壓制掉,從而不出現警告的提示。
一般有以下幾種:
@SuppressWarnings("unchecked")
告訴編譯器忽略 unchecked 警告資訊,如使用List,ArrayList等未進行引數化產生的警告資訊。
· @SuppressWarnings("serial")
如果編譯器出現這樣的警告資訊:The serializable class WmailCalendar does notdeclare a static final serialVersionUID field of type long
使用這個註釋將警告資訊去掉。
· @SuppressWarnings("deprecation")
如果使用了使用@Deprecated註釋的方法,編譯器將出現警告資訊。
使用這個註釋將警告資訊去掉。
· @SuppressWarnings("unchecked", "deprecation")
告訴編譯器同時忽略unchecked和deprecation的警告資訊。
· @SuppressWarnings(value={"unchecked", "deprecation"})
等同於@SuppressWarnings("unchecked", "deprecation")
參考書籍是人民郵電的《Java從入門到精通》,筆記中的部分例子和釋義是基於這本書寫的,也有一些來自網路。