到目前為止,我們都使用簡單類型作為方法的參數。但是,給方法傳遞對象是正確的,也是常用的。例如,考慮下面的簡單程序:
// Objects may be passed to methods.class Test { int a,b;
Test(int i,int j) {a = i; b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) { Test ob1 = new Test(100,22);Test ob2 = new Test(100,22);Test ob3 = new Test(-1,-1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
該程序產生如下輸出:
ob1 == ob2: true
ob1 == ob3: false
在本程序中,在Test 中的equals() 方法比較兩個對象的相等性,并返回比較的結果。也就是,它把調用的對象與被傳遞的對象作比較。如果它們包含相同的值,則該方法返回值為真,否則返回值為假。注意equals 中的自變量o指定Test 作為它的類型。盡管Test 是程序中創建的類的類型,但是它的使用與Java 的內置類型相同。
對象參數的最普通的使用涉及到構造函數。你經常想要構造一個新對象,并且使它的初始狀態與一些已經存在的對象一樣。為了做到這一點,你必須定義一個構造函數,該構造函數將一個對象作為它的類的一個參數。例如,下面版本的Box 允許一個對象初始化另外一個對象:
// Here,Box allows one object to initialize another.
class Box { double width; double height; double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.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 uninitializeddepth = -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 OverloadCons2 {
public static void main(String args[]) { // create boxes using the various constructorsBox mybox1 = new Box(10,20,15);Box mybox2 = new Box();Box mycube = new Box(7);
Box myclone = new Box(mybox1);
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 cube is " + vol);
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
在本程序中你能看到,當你開始創建你自己的類的時候,為了方便高效的構造對象,必須為同一構造函數方法提供多種形式。
原文轉自:http://www.anti-gravitydesign.com