帶你了解Java中Static關鍵字的用法
public class Student { private static int number;//靜態(tài)變量 private String name;//非靜態(tài)變量 public static void main(String[] args) {System.out.println(Student.number);System.out.println(Student.name);//會報錯 因為非靜態(tài)成員變量不能通過類名+屬性名調(diào)用 }}2. Static 修飾類方法,可以通過類名.靜態(tài)方法名的方式調(diào)用靜態(tài)方法,不可以用類名.靜態(tài)方法名調(diào)用非靜態(tài)方法;
public class Student { public static void go(){};//靜態(tài)方法 public void run(){};//非靜態(tài)方法 public static void main(String[] args) {Student.go();//可以用類名.靜態(tài)方法名的方式調(diào)用靜態(tài)方法Student.run();//報錯,不可以用類名.靜態(tài)方法名調(diào)用非靜態(tài)方法 }}3. 靜態(tài)代碼塊,匿名代碼塊,構(gòu)造函數(shù)。三者的調(diào)用順序為(靜態(tài)代碼塊(只調(diào)用1次) --> 匿名代碼塊 --> 構(gòu)造函數(shù))。
public class Student { //匿名代碼塊,每創(chuàng)建一個student對象就會調(diào)用一次匿名代碼塊 {System.out.println('調(diào)用匿名代碼塊'); } //靜態(tài)代碼塊,和類加載一起發(fā)生,只會調(diào)用一次 static {System.out.println('調(diào)用靜態(tài)代碼塊'); } //構(gòu)造函數(shù),每創(chuàng)建一個student對象就會調(diào)用一次該方法 public Student() {System.out.println('調(diào)用構(gòu)造函數(shù)'); } public static void main(String[] args) {new Student();new Student(); }}
【第三點 測試結(jié)果】
本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關注好吧啦網(wǎng)的更多內(nèi)容!
相關文章:
1. python實現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法3. ASP中格式化時間短日期補0變兩位長日期的方法4. 解析原生JS getComputedStyle5. HTML5 Canvas繪制圖形從入門到精通6. WML語言的基本情況7. XHTML 1.0:標記新的開端8. ASP基礎入門第八篇(ASP內(nèi)建對象Application和Session)9. xpath簡介_動力節(jié)點Java學院整理10. JSP的Cookie在登錄中的使用
