在本例中,Box() 建構函式需要三個自變數,這意味著定義的所有Box對象必須給Box() 建構函式傳遞三個參數。
例如,下面的語句在當前情況下是無效的:
Box ob = new Box();
因為Box( )要求有三個參數,因此如果不帶參數的調用它則是一個錯誤。
這會引起一些重要的問題。如果你只想要一個盒子而不在乎 (或知道)它的原始的尺寸該怎麼辦?
或,如果你想用僅僅一個值來初始化一個立方體,而該值可以被用作它的所有的三個尺寸又該怎麼辦?
如果Box 類是像現在這樣寫的,與此類似的其他問題你都沒有辦法解決,因為你只能帶三個參數而沒有別的選擇權。 幸好,解決這些問題的方案是相當容易的:重載Box 建構函式,使它能處理剛才描述的情況。
下面程式是Box 的一個改進版本,它就是運用對Box建構函式的重載來解決這些問題的:
/* Here,Box defines three constructors to initialize the dimensions of a box various ways. */
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w,double h,double d) {
width = w; height = h; depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; //
box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}/
/ /compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10,20,15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
該程式產生的輸出如下所示:
Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0 在本例中,當new執行時,根據指定的自變數調用適當的建構函式。