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

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

问题描述

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 时,您是在复制对象 references - 您不是在复制对象 - 所以变量 e1e2 都将指向同一个对象.

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天全站免登陆