全局變量在main方法中出現(xiàn)不能將一個非靜態(tài)變量賦值給靜態(tài)變量
public?class?HelloWorld?{ ?static?int?var=1;//去掉static就不對了,為什么 ?void?call() ?{?int?cal; ?System.out.println("var:"+var);} ? ?void?sendMessage() ?{int?cal; ??System.out.println("var"+var);} ? ?public?static?void?main(String[]?args)?{ ????//int?var=5; ????HelloWorld?phone=new?HelloWorld(); ??phone.call(); ??System.out.println(var);//為什么var一定要是static類型,如果不是static就會報錯 ???????} ????????}
2015-08-11
”不能將非靜態(tài)變量賦值給靜態(tài)變量“,這個一個標(biāo)準(zhǔn)的蠢貨級別定義,新手很容易因為這種被蠢貨總結(jié)的”經(jīng)驗“失去了刨根問底的動力。
原理:
static為類加載的時候執(zhí)行,發(fā)生在創(chuàng)建對象之前,此時非static可以理解為還未"出生"。
而非static需要在創(chuàng)建對象的時候才可以使用。
所以如果static的方法和屬性都不能調(diào)用非static,而反之可以。
2015-08-15
thanks a lot
2015-08-09
main函數(shù)是static