教程中国
PHOTOSHOP CS9.0中文版 MAYA 8.5 FOR WINDOWS Corel Painter v9.0 Flash MX2004 中文版 Illustrator cs2 中文版
VC++6.0含sp6 中英文版 VB6.0 +sp6 简体中文版 Borland Delphi 7汉化版 MSDN for vb6.0中文版 Visual Studio 2005简体
教程中国下属 文件存储共享专家BIBIDU.COM 提供大型软件,教材,源码,电影,音乐,图书等下载 更多精品请点此进入
  您目前所在位置: 教程中国 >> 编程基地 >> JAVA >> 把对象作为参数 RSS订阅
把对象作为参数
教程(视频,书籍)下载:  ASP.NET AutoCAD 数据库 C# ASP java photoshop 网页设计 delphi 3dmax Flash C++ VB 张孝祥 实例   更多请进入BIBIDU搜索
IT搜索引擎   
   

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

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

}
}

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

来源:编程技术-十度教育
作者:
关键字:象作为参数
发表日期:2006-10-18 13:43:09

网页显示有限 阅读全文请下载本文完整版WORD文档

上一篇:JAVA 方法重载   下一篇:java 参数是如何传递的


2008-10-8 7:12:05
本文的相类似文章
在学习中进步 在进步中成长 教程中国相随您的成长之路
华腾联合科技股份有限公司版权所有
广告联系:Rosibo@163.com