close

Static這個關鍵字有些人理解是維一的意思,其實他指的是這個屬性是放在類別(class)那一層,不隨著物件(object)的變更去改動的,非static的屬性,每一個物件會有一個值
所以物件A的值改變了,物件B的值並不會改變,但是static的屬性你不管使用物件A、物件B去更動他的值,他的值就是固定在類別上,所以會一起更動,所以他有另一個特性:可以用類別名稱去呼叫,最簡單的例子就像是Math.pow()這種方法(method)一樣,他是static的,如果這個方法還是自己類別的static方法,甚至可以省略類別名稱直接打上方法,以下是程式範例







public class StaticDemo {



public static void main(String[] args) {

StaticDemo obj1 = new StaticDemo();

StaticDemo obj2 = new StaticDemo();

System.out.println("method1:");

System.out.println(obj1.method1());//1

System.out.println(obj2.method1());//1



System.out.println(obj1.method1());//2

System.out.println(obj2.method1());//2



System.out.println("method2:");

System.out.println(StaticDemo.method2());//1

System.out.println(method2());//2

System.out.println(obj1.method2());//3

System.out.println(obj2.method2());//4



}



private int i1=0;

public int method1(){

i1++;

return i1;

}



private static int i2=0;

//private int i2=0;  //this will compile error

public static int method2(){

i2++;

return i2;

}

}

特別注意的是static的方法裡,要使用這個class的屬性的話,那個屬性就必須是static
不然你就要在裡面new一個自己類別的物件出來使用這個屬性,像是public static void main裡面那樣

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Dnight 的頭像
    Dnight

    D奈老師的部落格

    Dnight 發表在 痞客邦 留言(0) 人氣()