将对象用作参数

给方法传递对象是正确的,也是常用的。例如:

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

}

当开始创建自己的类时,为了能够以方便高效的方式构造对象,通常需要提供多种形式的构造函数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值