Java例項說明 靜態方法和非靜態方法的區別
阿新 • • 發佈:2019-02-04
程式碼:
public class OuterMyTest {
private static int a ;
private int b ;
public OuterMyTest(){
a += 1;
b += 1;
//System.out.println( "a = " + a + "; b = " + b );
}
public void getFun(){
System.out.println(b);
}
public static void main(String[] args) {
int c =1;
System.out.println(c);
OuterMyTest a1 = new OuterMyTest();
OuterMyTest a2 = new OuterMyTest();
System.out.println(a);
getFun();//報錯
OuterMyTest.getFun();//報錯
a1.getFun(); //通過
}
}
編譯報錯:Cannot make a static reference to the non-static method getFun() from the type OuterMyTest
改進:a1.getFun();
或者public static void getFun(){
System.out.println(b);
}
原因:
靜態方法只能訪問靜態成員,因為非靜態方法的呼叫要先建立物件,在呼叫靜態方法時可能物件並沒有被初始化。
OuterMyTest是一個類名,用類名只能調靜態方法,getFun是非靜態方法,所以要在物件上面呼叫,先要獲取一個
OuterMyTest類的物件 OuterMyTest a1 = new OuterMyTest();然後再呼叫a1.getFun();