Java基础:把对象作为参数

139 阅读2分钟

在学习Java的时候总会遇到一些问题,今天就给大家说下如何把对象作为参数。 到目前为止,我们都使用简单类型作为方法的参数。但是,给方法传递对象是正确的,也是常用的。例如,考虑下面的简单程序:

// 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(10022); 
  Test ob2 = new Test(10022); 
  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 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 OverloadCons2 { 
 public static void main(String args[]) { 
// create boxes using the various constructors 
 Box mybox1 = new Box(102015); 
 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); 
 } 
}

在本程序中你能看到,当你开始创建你自己的类的时候,为了方便高效的构造对象,必须为同一构造函数方法提供多种形式。