【问题标题】:The object does not change after being passed through a constructor. Why? [duplicate]对象在通过构造函数后不会改变。为什么? [复制]
【发布时间】:2016-09-22 09:01:21
【问题描述】:

您好,我有以下代码:

public class Dog {
    private String name;
    private int size;
    public Dog(String name, int size){
        this.name = name;
        this.size = size;
    }
    public void changeSize(int newSize){
        size = newSize;
    }
    public String toString(){
        return ("My name "+name+" my size "+ size);
    }
}

public class PlayWithDog {
    public PlayWithDog(Dog dog){
        dog = new Dog("Max", 12);
    }

    public void changeDogSize(int newSize, Dog dog){
        dog.changeSize(newSize);
    }


    public static void main(String[] args){
        Dog dog1 = new Dog("Charlie", 5);
        PlayWithDog letsPlay = new PlayWithDog(dog1); 
        System.out.println(dog1.toString()); // does not print Max.. Prints Charlie... .. Does not change... WHYYY???
        letsPlay.changeDogSize(8, dog1);
        System.out.println(dog1.toString()); // passing by value.. Expected Result... changes the size
        dog1 = new Dog("Max", 12);
        System.out.println(dog1.toString()); // Expected result again.. prints Max
    }
}

我知道 Java 总是按值传递所有内容。无论是原始类型还是对象。然而,在对象中,引用是传递的,这就是为什么您可以在对象通过方法传递之后对其进行修改的原因。我想测试当对象通过不同类的构造函数传递时是否同样适用。我发现对象没有改变。这对我来说似乎很奇怪,因为我只是在构造函数中传递对象的引用。它应该改变......?

【问题讨论】:

  • 您没有更改(变异)作为参数传递的对象,而是更改(重新分配)构造函数中的变量。这一切都在副本中进行了解释。

标签: java object constructor pass-by-reference pass-by-value


【解决方案1】:

我知道 Java 总是按值传递所有内容

这正是你的构造函数对传入的对象不做任何事情的原因。你可以改变传入对象的状态,但你不能改变原始变量的引用。

【讨论】:

    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 2018-01-29
    • 2020-02-29
    • 2016-10-22
    • 2012-11-24
    • 2021-05-14
    • 2019-08-18
    • 2014-03-12
    相关资源
    最近更新 更多