Static? • 靜態? class Test { static int static. X; int instance. X; public Test(int var 1, int var 2) { this. static. X = var 1; this. instance. X = var 2; } } • 差別在於,instance. X是一個”instance member”,而 static. X是一個”class member”
當我們產生很多物件時… • • Test obj 1 = new Test(1, 2); Test obj 2 = new Test(3, 4); Test obj 3 = new Test(5, 6); 物件obj 1, obj 2, obj 3所指向的實體,會各自 有各自的instance. X – System. out. println(obj 1. instance. X); //印出 2 – System. out. println(obj 2. instance. X); //印出 4 – System. out. println(obj 3. instance. X); //印出 6
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; } }
Example 2: 數學 class Math { public static final double PI = 3. 1415926; } • 我們會使用 Math. PI 來取得這個公定的常數
用在 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 get. Rate() { return rate; } }