1. 程式人生 > >"靜態方法裡只能呼叫靜態變數和靜態方法"詳解

"靜態方法裡只能呼叫靜態變數和靜態方法"詳解

靜態方法裡可以呼叫靜態方法和靜態變數,同時也能呼叫非靜態方法和非靜態變數。

public class Test {

public Test() {};
public Test(int i) {this.n = i;}

public static int m = 5;
public int n = 10;

public void fun1() {System.out.println("非靜態方法fun1");}
public static void fun2() {System.out.println("靜態方法fun2");}

//測試“靜態方法裡只能呼叫靜態變數和靜態方法”具體是什麼意思
public static void main(String[] args) {
 //呼叫靜態方法不會報錯
 //fun2();

 //呼叫靜態變數不會報錯
 System.out.println(m);

 //無法從靜態上下文中引用非靜態方法fun1()
 //fun1();

 //無法從靜態上下文中引用非靜態變數n
 //System.out.println(n);

 //可以在靜態方法中new物件,呼叫到了非靜態方法的構造方法,不管是否預設構造方法,下列程式碼均能正確執行。故認為:“編譯階段,編譯器不會檢查靜態方法中牽扯到 具體物件以及物件的相關操作”。如此,也提供了靜態方法中訪問非靜態方法和非靜態屬性的解決方案。
 //Test t = new Test(8);
 //t.fun2();
 //t.fun1();
 //System.out.println(t.m);	
 //System.out.println(t.n);
 
}
}