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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | class Animal { private int age; private int weight; private static int number = 0 ; public Animal( int a, int w) { number++; setAge(a); setWeight(w); System.out.println( "Animal物件已建立...." ); } public Animal( int w) { number++; setAge( 3 ); setWeight(w); System.out.println( "Animal物件已建立...." ); } public Animal() { number++; setAge( 3 ); setWeight( 15 ); System.out.println( "Animal物件已建立...." ); } public int getAge() { return age; } public void setAge( int n) { if (n < 0 ) { age = 1 ; } else { age = n; } } public int getWeight() { return weight; } public void setWeight( int n) { if (n < 0 ) { weight = 1 ; } else { weight = n; } } public static int getNumber() { return number; } public void speak() { System.out.println( "哈囉,我已經" + getAge() + "歲,有" + getWeight() + "公斤重" ); } } class JungleDemo4 { public static void main(String[] args) { System.out.println( "動物有" + Animal.getNumber() + "隻" ); Animal puppy1 = new Animal( 6 , 70 ); puppy1.speak(); Animal puppy2 = new Animal( 142 ); puppy2.speak(); Animal puppy3 = new Animal(); puppy3.speak(); System.out.println( "動物有" + Animal.getNumber() + "隻" ); } } /* 《程式語言教學誌》的範例程式 檔名:JungleDemo4.java 功能:示範物件導向的基本觀念 作者:張凱慶 時間:西元 2010 年 10 月 */ |
編譯後執行,結果如下

首先在第 5 行
5 | private static int number = 0 ; |
這裡宣告一個 static 屬性,表示 number 屬於類別 Animal ,用來記錄一共有多少 Animal 物件被建立。因此在第 8 行、第 15 行及第 22 行的建構子中, number 都遞增 1
8 | number++; |
第 55 行,這是一個 static 方法,其屬於類別,因此可以直接以類別名稱便可使用
55 56 57 | public static int getNumber() { return number; } |
static 方法屬於類別,因此可以直接以類別名稱便可使用,例如第 66 行及第 77 行
55 | System.out.println( "動物有" + Animal.getNumber() + "隻" ); |
使用 static 成員需注意以下幾點
- 實例方法 (instance method) ,也就是非 static 方法可以直接使用其他實例變數 (instance variable) 及實例方法。
- 實例方法可以直接使用其他 static 變數,也就是類別變數 (class variable) ,及 static 方法,也就是類別方法 (class method) 。
- static 方法可以直接使用其他 static 變數,也就是類別變數,及 static 方法,也就是類別方法。
- static 方法不能直接使用其他非 static 變數,也就是實例變數,及非 static 方法,也就是實例方法。必須在 static 方法中建立物件,然後用物件的參考變數才可利用實例方法或實例變數。
中英文術語對照 | |
---|---|
成員 | member |
類別 | class |
物件 | object |
實例方法 | instance method |
實例變數 | instance variable |
類別變數 | class variable |
類別方法 | class method |
參考資料
http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html
http://download.oracle.com/javase/tutorial/java/javaOO/initial.html
http://java.sun.com/docs/books/jls/third_edition/html/classes.html
http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html
http://download.oracle.com/javase/tutorial/java/javaOO/initial.html
http://java.sun.com/docs/books/jls/third_edition/html/classes.html
1 則留言:
static 方法屬於類別,因此可以直接以類別名稱便可使用,例如第 66 行及第 77 行
下面的代码行数是错误的,你们写成55行了
而且按照这个意思,下面的
System.out.println("動物有" + Animal.getNumber() + "隻");
Animal.getNumber()应该是没有Animal. 才对啊,直接以類別名稱便可使用
張貼留言