Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is passing object to constructor pass by reference [duplicate]

Suppose I have a class and constructor called TestClass.

public class TestClass {
    Foo foo;

    public TestClass(Foo foo) {
        this.foo = foo; 
    }
}

Here, the constructor accepts an object which is an instance of class Foo. Suppose my static void main(String[] args) does the following, completely separate from any TestClass;

  • (1) Instantiate foo

  • (2) Pass instance foo to TestClass constructor

  • (3) Change the internal state of foo

After step (3), will the foo within my instance of TestClass also have its state changed?

like image 546
user2763361 Avatar asked Oct 21 '13 02:10

user2763361


Video Answer


2 Answers

It is not passed by reference. Rather, it is passed by value of the reference, which is a subtle but important distinction.

After you mutate foo in the rest of your main() method, the foo field will also exhibit these mutations, as you state, since both variables point to the same instance. However, if you reassign foo to something new, the foo field will not be changed. This would not be true if foo were truly passed by reference. In short, everything is passed by value in Java; it just so happens that objects are dealt with by reference, and so the values of these references are passed.

I'll try to illustrate this with an example. Consider the following class:

class A {
    public int n;

    public A(int n) {
        this.n = n;
    }
}

and the following method:

public static void mutate(A a) {
    a.n = 42;
}

Now we can have something like this:

A a = new A(0);
A.mutate(a);

System.out.println(a.n);
42

We can see that the state of a was changed in mutate(). Now let's modify the static method:

public static void mutate(A a) {
    a = new A(42);
}

and try again:

A a = new A(0);
A.mutate(a);

System.out.println(a.n);
0

As you can see, the state of a is unchanged. If the reference had been passed to the function, we would expect the effect of the reassignment to be evident beyond the scope of the method. Nevertheless, some reference was in fact passed, since mutating the argument caused changes outside of the method as well.

like image 94
arshajii Avatar answered Sep 18 '22 00:09

arshajii


enter image description hereYes, because you are assigning same object to another reference of Foo class, i.e. object is same, but being referred by two reference.

like image 40
codingenious Avatar answered Sep 20 '22 00:09

codingenious