1.如何创建对象
首先建立一个Fighterplane类
public class FighterPlane{
String name;
int missileNum;
void fire(){
if (missileNum>0)
{ missileNum-=1;
System.out.println("new fire a missile");}
else
{ System.out.println("No missile left");}
}
}
下面用FighterPlane类来创建一个对象,对应语句如下:
FighterPlane fp = new FighterPlane();
2.分析
上述创建对象的语句可以理解为以下四个步骤:
- 右边的 new FighterPlane 是以 FighterPlane 为类模板,在堆空间上创建了一个 FighterPlane 对象。
- 末尾的( )意味着,在对象创建后,立即调用 FighterPlane 类的构造函数,对刚生成的对象进行初始化。
- 左边的 FighterPlane fp 声明了一个FighterPlane 类对象引用,它存放在栈空间中。也就是用来指向 FighterPlane 对象的对象引用。
- 语句中的 “=” 表示初始化对象引用 fp = new FighterPlane()。
该过程如图所示:
该语句的实质是将新创建的 FighterPlane 对象的地址赋给对象引用 fp,从此 fp 与该对象关联,通过 fp 即可操纵该对象。
3.对象作为参数的特点
【举例1】
public class PassPara{
private static int a;
public static void main(String [] args) {
modify(a);
System.out.println(a);
}
public static void modify(int a) {
a++;
}
本程序输出结果为0。
解释:当modify方法调用完毕后,栈空间被释放,形式参数a也被释放,无法回传给静态变量a。a++是对形式参数进行自增,而不是类属性a进行自增。
对象是引用传递,当对象作为参数传递时,传递的是对象的地址。
【举例2】
class IntClass{
int value;
}
public class RunIntClass{
public static void modifyValue(IntClass s, int val) {
s.value = val;
}
public static void main(String args[]) {
IntClass a = new IntClass();
modifyValue(a,8);
System.out.println(a,value);
}
}
解释:本例中 “s = a” 的含义是将a的地址传递给s,而不是产生了新的对象,这样s和a所指的对象是同一个。此时,在方法modifyValue内部,通过s进行对象的赋值,改变了堆中引用对象的属性值。
【举例3】
FighterPlane fp = new FighterPlane ();
FighterPlane fp1 = new FighterPlane ();
FighterPlane fp2 = fp;
FighterPlane fp3;
fp3 = fp1;
用图表示该过程: