What is static Static class Test static int
- Slides: 11
What is static?
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; } }
Static method • 不存在任何實體即可使用,則 • System. out. println( Account. get. Rate() ); //印出 0. 002 • 雖然我們也可以產生實體後再以實體的 reference variable來存取 – Account acc 1 = new Account(“John”, 1000); – System. out. println( acc 1. get. Rate() ); • 但是這樣的寫法是”不被建議的”,造成誤解, 雖然compile可以過,但Eclipse會警告,要你改 成Account. get. Rate()
更Advance的問題 • Class. Loader? • 有一個class,名字叫做java. lang. Class (注意 大小寫) – 前者是說”有一個類別” – 後者是說”這個類別名字叫java. lang. Class” • 有一種寫法 – Class klass = Class. for. Name(“java. lang. String”); – klass. new. Instance(); • Why?
- Interface calculator public int add class test
- Int sum(int a int n) int sum=0 i
- Int max(int x int y)
- Public void drawsquare(int x, int y, int len)
- Public int divide(int a int b)
- Public class welcome
- Class math static int x
- Public class test subject extends test class
- Interface myinterface int foo(int x)
- Int main int argc char argv
- #include stdio.h void main()
- 7팩토리얼