Kevin Shaughnessy
Kevin Shaughnessy

Reputation: 19

Class attribute variables - are references or a new object stored?

Say I have a code:

public static void main(String[] args) {
    Animal r1 = new Animal(10,"Amanda");
    House c = new House(100, r1);
    r1.setAge(3);
    
    House c2 = new House(101, r1);
    System.out.println(c);
    System.out.println(c2);
}

The output is

3 Amanda

3 Amanda

So it looks like what java does is store a reference to r1 in the Animal field value in House so that any changes to the object itself are reflected in any call to the Animal variable in the House class. Is that it? Or does java create a whole new object?

Upvotes: 1

Views: 767

Answers (2)

MC Emperor
MC Emperor

Reputation: 23017

Your assumption is correct. Java stores a reference to the animal pointed to by r1.

Note that this is not the same as pass-by-reference. Java is always pass-by-value, but the values themselves are references.

That means that if you call the constructor of House and within the constructor, you assign a new object to the passed in variable, then this won't be reflected to the outside.

public House(int id, Animal animal) {
    animal = new Animal(11, "Bertha");
}
Animal r1 = new Animal(10,"Amanda");
House c = new House(100, r1);
System.out.println(r1);

So the abovementioned println still prints "Amanda" (and not "Bertha"). The variable r1 passed into the constructor is not the same as the animal variable used within the constructor. The value of the reference of r1 is copied into animal. Reassigning animal has no effect on r1.

Upvotes: 1

user7655213
user7655213

Reputation:

Both of these House objects share a reference to the same Animal object, just as you suspected.

Note that this behavior is only for objects, not for primitives (int, boolean, float, double, char, ...)

Upvotes: 0

Related Questions