以Instance來說,Class只是一個模型,在new的時候複製一份至每個物件的記憶體空間中,因此每個物件中的元素互相不共用
而Static則是將元素限定於Class本身的記憶體,new的時候是將元素本身的參照存至物件記憶體中,而非複製,此外也能直接透過Class本身去存取該元素
Instance範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class test { public static void main(String args[]) { Foo bar; // 產生一個名為bar的Foo空物件 bar = new Foo(); // 將Foo複製到物件bar bar.setFoobar( 35 ); // 設定bar物件中的foobar變數 bar.getFoobar(); // 回傳bar物件中的foobar變數 } } class Foo { private int foobar; void setFoobar( int foobar) { this .foobar = foobar; // 設定當前物件(this)的foobar變數 } int getFoobar() { return this .foobar; // 回傳當前物件(this)的foobar變數 } } |
對Instance來說Class只是一個模型,所以this是指當前物件,在new給物件之前,這並沒有指向任何東西
Static範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class test { public static void main(String args[]) { // 透過物件存取,不建議這樣使用 Foo bar; // 建立名為bar的Foo物件 bar = new Foo(); // 將Foo複製到物件bar bar.setFoobar( 40 ); // 透過物件bar設定foobar變數 bar.getFoobar(); // 透過物件bar取回foobar變數 // 直接存取 Foo.setFoobar( 35 ); // 透過Class本身的方法去設定foobar變數 Foo.getFoobar(); // 透過Class本身的方法回傳foobar變數 } } class Foo { private static int foobar; static void setFoobar( int foobar) { Foo.foobar = foobar; // 將Class的foobar設為傳入變數foobar } static int getFoobar() { return Foo.foobar; // 回傳Class的foobar變數 } } |
留言