What is static?

11
What is static?

description

What is static?. Static?. 靜態 ? class Test { static int staticX ; int instanceX ; public Test( int var1, int var2) { this.staticX = var1; this.instanceX = var2; } } 差別在於, instanceX 是一個 ”instance member” ,而 staticX 是一個 ”class member”. 當我們產生很多物件時 …. Test obj1 = new Test(1,2); - PowerPoint PPT Presentation

Transcript of What is static?

Page 1: What is static?

What is static?

Page 2: What is static?

Static?• 靜態 ?class Test {

static int staticX;int instanceX;

public Test(int var1, int var2) {this.staticX = var1;this.instanceX = var2;}

}• 差別在於, instanceX 是一個” instance member” ,而 staticX 是

一個” class member”

Page 3: What is static?

當我們產生很多物件時…• Test obj1 = new Test(1,2);• Test obj2 = new Test(3,4);• Test obj3 = new Test(5,6);• 物件 obj1, obj2, obj3 所指向的實體,會各自

有各自的 instanceX– System.out.println(obj1.instanceX); // 印出 2– System.out.println(obj2.instanceX); // 印出 4– System.out.println(obj3.instanceX); // 印出 6

Page 4: What is static?

但 static variable 不同• Static variable 不屬於任何一個 instance• 上述的程式順著執行下來, staticX 的值被

依序改成 1 , 3 , 5– 他們改的是同一份 !– Static variable 屬於 “ class 所有”– this.staticX = 3 ,其實等價於寫 Test.staticX = 3

Page 5: What is static?

什麼時候用得到 ?

• 建立一個 class 來代表銀行的帳戶• 每個帳戶有名字,有他們存的錢的數量,

以及銀行利率– 每個人的戶名不同– 每個人存的錢數量不同– 銀行利率是統一的 ! 大家都一樣

Page 6: What is static?

Example: Account.java

class Account {int money;String name;static double rate = 0.002; //0.2%public Account(String name, int money) {

this.name = name;this.money = money;

}}

Page 7: What is static?

Example2: 數學class Math {

public static final double PI = 3.1415926;}

• 我們會使用 Math.PI 來取得這個公定的常數

Page 8: What is static?

用在 Method 時呢 ?• 不需要有 instance ,即可以使用• 再看 Account 的例子class Account {

private int money;private String name;private static double rate = 0.002; //0.2%public Account(String name, int money) {

this.name = name;this.money = money;

}public static double getRate() {

return rate;}

}

Page 9: What is static?

Static method

• 不存在任何實體即可使用,則• System.out.println( Account.getRate() ); // 印出

0.002• 雖然我們也可以產生實體後再以實體的 reference

variable 來存取– Account acc1 = new Account(“John”, 1000);– System.out.println( acc1.getRate() );

• 但是這樣的寫法是”不被建議的”,造成誤解,雖然 compile 可以過,但 Eclipse 會警告,要你改成 Account.getRate()

Page 10: What is static?

Discussion

• 為什麼我 compile 常看到 compiler 說,你不能在 static method 存取 non-static variables?– Static method 本來就存在,實體不存在當然不能

存取– 即使實體存在,也不知道你想存取”哪一個實體

”• 為什麼 main 要宣告成 static?– 一開始總要有個進入點,讓程式開始執行– 如果不使用 static 修飾字,則一定要 new 了之後產

生實體才能使用,那麼就無從開始了

Page 11: What is static?

更 Advance 的問題• ClassLoader?• 有一個 class ,名字叫做 java.lang.Class ( 注意

大小寫 )– 前者是說”有一個類別”– 後者是說”這個類別名字叫 java.lang.Class”

• 有一種寫法– Class klass = Class.forName(“java.lang.String”);– klass.newInstance();

• Why?