将对象分配给另一个对象时会发生什么 [英] What happens when an object is assigned to another object

查看:160
本文介绍了将对象分配给另一个对象时会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class DrumKitTestDrive {
/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Echo e1 = new Echo();
    Echo e2 = new Echo();
//      **e2 = e1;**

    int x=0;
    while( x < 4 ){
        e1.hello();
        e1.count = e1.count + 1;
        if(x==3){
            e2.count = e2.count + 1;
        }
        if(x>0){
            e2.count = e2.count + e1.count;
        }
        x = x + 1;
    }
    System.out.print(e2.count);
    }
}

class Echo {
    int  count = 0;

    void hello(){
        System.out.println("Hellooooo....");
    }
}

此代码的输出将为:

Hellooooo....
Hellooooo....
Hellooooo....
Hellooooo....
10

但如果我从删除评论// e2 = e1; 当我运行代码时,系统将打印 24 而不是 10 。我不明白为什么会这样?

But if I remove the comments from // e2= e1; when I run the code the system will print 24 instead of 10. I don't understand why is it so?

据我所知,系统只会复制 e1的值实例进入 e2 实例。如果系统会这样做,结果将保持不变,因为两个对象属于同一类。

What I understand is the system will just copy the values of e1 instance into e2 instance. And if the system will do so, the result shall remain the same because both objects are of the same class.

推荐答案


据我所知,系统只会将e1实例的值复制到e2实例中。

What I understand is the system will just copy the values of e1 instance into e2 instance.

不,当你做 e2 = e1 你正在复制对象引用 - 你没有复制对象 - 所以变量 e1 e2 都会指向同一个对象

No, when you do e2 = e1 you're copying object references - you're not making a copy of the object - and so the variables e1 and e2 will both point to the same object.

所以当你做增量时,它们都会递增相同的计数字段。

And so when you do your increments, they're all incrementing the same count field.

它只有没有赋值 e2 = e1 增量发生在两个不同的实例上。

It's only without the assignment e2 = e1 that the increments are happening on two different instances.

这篇关于将对象分配给另一个对象时会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆