帶你了解Java中Static關(guān)鍵字的用法
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);//會(huì)報(bào)錯(cuò) 因?yàn)榉庆o態(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();//報(bào)錯(cuò),不可以用類名.靜態(tài)方法名調(diào)用非靜態(tài)方法 }}3. 靜態(tài)代碼塊,匿名代碼塊,構(gòu)造函數(shù)。三者的調(diào)用順序?yàn)椋o態(tài)代碼塊(只調(diào)用1次) --> 匿名代碼塊 --> 構(gòu)造函數(shù))。
public class Student { //匿名代碼塊,每創(chuàng)建一個(gè)student對(duì)象就會(huì)調(diào)用一次匿名代碼塊 {System.out.println('調(diào)用匿名代碼塊'); } //靜態(tài)代碼塊,和類加載一起發(fā)生,只會(huì)調(diào)用一次 static {System.out.println('調(diào)用靜態(tài)代碼塊'); } //構(gòu)造函數(shù),每創(chuàng)建一個(gè)student對(duì)象就會(huì)調(diào)用一次該方法 public Student() {System.out.println('調(diào)用構(gòu)造函數(shù)'); } public static void main(String[] args) {new Student();new Student(); }}
【第三點(diǎn) 測試結(jié)果】
本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注好吧啦網(wǎng)的更多內(nèi)容!
相關(guān)文章:
1. moment轉(zhuǎn)化時(shí)間戳出現(xiàn)Invalid Date的問題及解決2. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊3. Java剖析工具YourKit 發(fā)布5.0版本4. 跟我學(xué)XSL(一)第1/5頁5. 為什么你的android代碼寫得這么亂6. 使用JSP技術(shù)實(shí)現(xiàn)一個(gè)簡單的在線測試系統(tǒng)的實(shí)例詳解7. Python中內(nèi)建模塊collections如何使用8. 解決VUE項(xiàng)目localhost端口服務(wù)器拒絕連接,只能用127.0.0.1的問題9. 開發(fā)效率翻倍的Web API使用技巧10. 動(dòng)態(tài)設(shè)置django的model field的默認(rèn)值操作步驟
