为什么对象" person1"和对象" person2"是相同的?

时间:2014-11-11 03:01:10

标签: java object pseudocode

在此程序中,每当您更改person1或person 3时,它们将包含相同的值。我尝试在伪代码中完成每一步,但是我总是在这两个对象背后的推理中迷失方向。你能帮忙解释一下这些步骤吗?我真的很想了解。谢谢你的时间。

public class References1
{
    public static void main (String[] args)
    {
        Person person1 = new Person ("Rachel", 6);
        Person person2 = new Person ("Elly", 4);
        Person person3 = new Person ("Sarah", 19);

        System.out.println ("\nThe three original people...");
        System.out.println (person1 + ", " + person2 + ", " + person3);

        // Reassign people
        person1 = person2;
        person2 = person3;
        person3 = person1;


        System.out.println("\nThe three people reassigned...");
        System.out.println (person1 + ", " + person2 + ", " + person3);

        System.out.println();
        System.out.println ("Changing the second name to Bozo...");
        person2.changeName ("Bozo");
        System.out.println (person1 + ", " + person2 + ", " + person3);

        System.out.println();
        System.out.println ("Changing the third name to Clarabelle...");

        person3.changeName ("Clarabelle");
        System.out.println (person1 + ", " + person2 + ", " + person3);
        System.out.println();
        System.out.println ("Changing the first name to Harpo...");
        person1.changeName("Harpo");
        System.out.println (person1 + ", " + person2 + ", " + person3);
    }
}

4 个答案:

答案 0 :(得分:3)

这些是造成问题的原因:

// Reassign people
person1 = person2;
person2 = person3;
person3 = person1;

如果变量具有以下起始值:

person1 = "A";
person2 = "B";
person3 = "C";

...然后你通过你的代码运行它:

person1 = person2 -> person1 is now set to "B" (the value "A" is discarded)

person2 = person3 -> person2 is now set to "C"

person3 = person1 -> person3 is now set to the value of person1 which is "B"

所以现在变量person1和person3被设置为同一个对象。

答案 1 :(得分:2)

person1person3指的是同一物理object,即person2。所有这些都是因为这些任务:

person1 = person2;    
person3 = person2;

答案 2 :(得分:1)

您的Person引用指向相同的Person对象。以下是您的作业效果的说明。 enter image description here

答案 3 :(得分:0)

“在此程序中,每当您更改person1或person 3时,它们将包含相同的值......”。

不完全:

1)你用person1 = person2;使Rachel“孤儿”,然后你成为了Sarah的孤儿。最后,变量person1和person3 同时参考相同的对象(Elly)。

2)此时,Rachel和Sarah的对象都有资格进行垃圾回收:无法访问它们。

3)此外,您对“Elly”所做的任何更改都将反映在所有三个变量中。因为这三个都引用了相同的底层对象。

这是一个很好的链接,可以更详细地解释“对象引用”的概念:

References to objects