您的位置:首页 > 编程语言 > Java开发

thinking in java test3.4练习(2)(3)别名机制

2016-08-01 08:53 435 查看
题目:创建一个包含float域的类,并用这个类来展示别名机制。

别名机制是指多个引用指向同一个对象。

我们知道Java里操作对象一般是通过引用来完成的,而引用的指一般是所指向的对象的内存地址。比如有两个引用a1,a2,分别指向两个对象。此时进行a1 = a2操作,这个操作的结果是把a2的值赋给了a1,也就是a1之后也指向了a2。a1之前引用的对象将会在某个时刻被垃圾回收器自动清理。 这就是别名对象。

public class test3_2 {
public static void main(String [] args) {
Peopel xiaoMing = new Peopel();
Peopel xiaoHong = new Peopel();
xiaoMing.height = 2.10f;
xiaoHong.height = 1.68f;
System.out.println("xiaoMing : " + xiaoMing.height + "    xiaoHong : " + xiaoHong.height);
xiaoMing = xiaoHong;
System.out.println("xiaoMing : " + xiaoMing.height + "    xiaoHong : " + xiaoHong.height);
xiaoMing.height = 1.96f;//此时操作的其实是xiaoHong的height
System.out.println("xiaoMing : " + xiaoMing.height + "    xiaoHong : " + xiaoHong.height);

}
}

class Peopel {
float height;
}


控制台输出:

xiaoMing : 2.1 xiaoHong : 1.68

xiaoMing : 1.68 xiaoHong : 1.68

xiaoMing : 1.96 xiaoHong : 1.96

上述程序中最后xiaoMing也指向了xiaoHong,这种现象就是别名现象。如果我们原本只是想把xiaoHong的height值传给xiaoMing,那么应该这样做:

xiaoMing.height = xiaoHong.height;

这样才不会出错。

在编程时我们应该注意这个问题,这个问题一不注意,就会造成巨大隐患。

那是不是别名现象一定就是有害的,应该完全避免呢?

其实不是的,在方法调用中,别名现象其实有很打用处。

我们来看下面这个题目:创建一个包含一个float域的类,并用这个类来展示方法调用时的别名机制。

书上有相应例子代码,我们对着模仿一个。

public class test3_2 {
public static void main(String [] args) {
Peopel xiaoMing = new Peopel();
xiaoMing.height = 2.10f;
System.out.println("xiaoMing" + xiaoMing.height);
growUp(xiaoMing);
System.out.println("xiaoMing" + xiaoMing.height);
}

static void growUp(Peopel p) {
p.height = p.height + 0.10f;
}
}

class Peopel {
float height;
}


这里看起来在静态方法growUp里操作的是p,其实因为别名机制,我们在方法调用时将xiaoMing的引用传递给了p,这里操作的其实是xiaoMing的height。

以上。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java