2008/11/02

[ Java ] About Constructor

Java 建構子 (Constructor) 範例:


class JCRectArea {
private int height, wide;

JCRectArea(){
height = wide = 1;
}
JCRectArea(int h){
SetHeight(h);
wide = 1;
}
JCRectArea(int h, int w){
SetHeight(h);
SetWide(w);
}
void SetHeight(int h){
height = h;
}
void SetWide(int w){
wide = w;
}
int GetArea(){
return height*wide;
}
}


public class JConstructor {
public static void main(String[] args){
JCRectArea a1 = new JCRectArea();
System.out.println("AREA ="+a1.GetArea());
JCRectArea a2 = new JCRectArea(5);
System.out.println("AREA ="+a2.GetArea());
JCRectArea a3 = new JCRectArea(3,6);
System.out.println("AREA ="+a3.GetArea());
}
}

輸出:

AREA =1
AREA =5
AREA =18

說明:

建構子(Constructor)宣告建立一個物件之同時也給予資料成員初始化之動作,類別的建構子也就是一種類別內部方法成員。建構子使用時須特別注意:

1.Constructor 定義的方式與 Method 相似。
2.Constructor 名稱會與類別名稱相同。
3.Constructor 不能使用修飾子也無回傳值所以不能使用 return 及 void。
4.Constructor 可以使用方法多載(Method Overloading)。

範例程式為一個計算矩形面積的程式,若矩形的邊長沒有設定值(系統預設為1)。在這個範例中有三個建構子每個建構子所配置的參數皆不同。

0 意見: