Passing an object to the constructor by reference

Suppose I have a class and constructor called TestClass.

public class TestClass {
    Foo foo;

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

Here, the constructor takes an object that is an instance of the class Foo. Suppose mine static void main(String[] args)does the following, completely separate from anyone TestClass;

  • (1) Instant Foo

  • (2) Skip the instance Fooin the TestClassconstructor

  • (3) Change the internal state Foo

After step (3), will the status Fooin my instance be changed TestClass?

+4
source share
3 answers

It is not transmitted by reference. Rather, it is passed by reference value, which is a subtle but important difference.

, foo main(), foo , , . , foo - , foo . , foo . , Java; , , .

. :

class A {
    public int n;

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

:

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

- :

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

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

, a mutate(). :

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

:

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

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

, a . , , . , , .

+13

enter image description here , Foo, .. , .

+3

(3) foo TestClass ?

.

this

...

, ...

public class TestClass {
    int foo;

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

    public String toString() {
        return "TestClass: " + foo;
    }
}

public static void main(String args[]) {
    int myFoo = 1;
    TestClass test = new TestClass(myFoo);
    myFoo += 2;
    System.out.println("myFoo = " + myFoo);
    System.out.println("yourFoo = " + test);
}

...

myFoo = 3
yourFoo = 1

, , /.

,

public class TestClass {
    Foo foo;

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

    public Foo getFoo() {
        return foo;
    }
}

public static void main(String args[]) {
    Foo myFoo = new Foo();
    TestClass test = new TestClass(myFoo);
    myFoo = new Foo();
    System.out.println("myFoo == yourFoo = " + myFoo.equals(test.getFoo()));
}

myFoo == yourFoo = false

.

0
source

All Articles