到目前為止,我們都使用簡單類型作為方法的參數。但是,給方法傳遞對象是正確的,也是常用的。例如,考慮下面的簡單程序:
// 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
新聞熱點
疑難解答