Search code examples
javaobjectconstructorpass-by-referencepass-by-value

The object does not change after being passed through a constructor. Why?


Hi I have the following code:

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
    }
}

I know Java always passes everything by value. Be it primitive types or objects. In objects however, the reference is passed that is why you can modify the object after its being passed through a method. I wanted to test whether the same thing applies when the object is passed through a constructor of a different class. I found out that the object does not get changed. This seemed weird to me because I am just passing a reference of the object in the constructor. It should change...?


Solution

  • I know Java always passes everything by value

    It's precisely why your constructor does nothing to the object passed in. You can change the state of the object passed in, but you can't change the reference of the original variable.