把对象作为参数

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

到目前为止,我们都使用简单类型作为方法的参数。但是,给方法传递对象是正确的,也是常用的。例如,考虑下面的简单程序:

// 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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航