为什么这个对象会在方法调用期间发生变化?

public class Person {
    private String name;
    private int birthYear;

    public Person(String name) {
        this.name = name;
        this.birthYear = 1970;
    }

    public int getBirthYear() {
        return this.birthYear;
    }

    public void setBirthYear(int birthYear) {
        this.birthYear = birthYear;
    }

    public String toString() {
        return this.name + " (" + this.birthYear + ")";
    }
}

public class Example {
    public static void main(String[] args) {
        Person first = new Person("First");

        System.out.println(first);
        youthen(first);
        System.out.println(first);

        Person second = first;
        youthen(second);

        System.out.println(first);
    }

    public static void youthen(Person person) {
        person.setBirthYear(person.getBirthYear() + 1);
    }
}

我的教程说输出将是:

public class Person {
    private String name;
    private int birthYear;

    public Person(String name) {
        this.name = name;
        this.birthYear = 1970;
    }

    public int getBirthYear() {
        return this.birthYear;
    }

    public void setBirthYear(int birthYear) {
        this.birthYear = birthYear;
    }

    public String toString() {
        return this.name + " (" + this.birthYear + ")";
    }
}

public class Example {
    public static void main(String[] args) {
        Person first = new Person("First");

        System.out.println(first);
        youthen(first);
        System.out.println(first);

        Person second = first;
        youthen(second);

        System.out.println(first);
    }

    public static void youthen(Person person) {
        person.setBirthYear(person.getBirthYear() + 1);
    }
}

我可以跟踪代码直到创建第二个 Person 对象。然后我不明白为什么在第二个 Person 对象上调用 youthen 方法会更改第一个 Person 对象。

在我看来,有两个 Person 对象。我们先改变了Person的出生年份,然后将Person first的实例变量值复制到Person second,然后我们使用youthen方法对Person second的实例变量值进行了操作,而Person first自上次调用它的方法以来没有改变. 我希望最终的打印方法返回

First (1970)
First (1971)
First (1972)

回答

直到第二个 Person 对象被创建

不。这段代码只创建一个Person对象。就在这儿:

new Person("First")

在任何时候都不会Person调用构造函数,因此不会在其他时候Person创建另一个对象。您拥有的是对同一对象的多个引用 Person

Person second = first;

打个比方,假设你有一所房子,你在两张纸上写下那所房子的地址。一个人使用他们的一张纸,走进房子并改变了一些东西。(例如,给它涂上新颜色。)然后第二个人用他们的纸去房子,他们看到了新颜色。因为只有一所房子,不管有多少人知道它的地址。

要创建第二个Person,请重新调用构造函数:

Person second = new Person("Second");


以上是为什么这个对象会在方法调用期间发生变化?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>