Mano Mano - 3 months ago 8
Java Question

Need help understanding the output of this code

I'm a beginner so it really doesn't get any simpler than this.

I got 2 separate .java files in a folder.

A class responsible for the "attributes" of a dog (name, age, breed etc).

...
public String name;
public byte age;
public String breed;

public String makeNoise()
{
return "Woof...";
}

public String toString()
{
return "Name: " +name +"\n" +"Age: " +age +"\n" +"Breed: " +breed;
}
...


And a Tester to test the dog class.

...
Dog d1 = new Dog();
d1.name = "Frodo";
d1.age = 4;
d1.breed = "Alsatian";

Dog d2 = new Dog();
d2.name = "Labby";
d2.age = 3;
d2.breed = "Labrador";

Dog d3 = d2;
d3.age = 6;
d3.name = "Mike";


System.out.println(d1.name);
System.out.println(d2.age);
System.out.println(d3.age);
System.out.println(d2.name);

System.out.println(d1.age == d2.age);
System.out.println(d1 == d2);
System.out.println(d1 == d3);
System.out.println(d2 == d3);
...


The output of

System.out.println(d2.age);


Is returning 6, for some reason, and I don't understand why. Any help would be much appreciated.

Answer

When you make the assignment

Dog d3 = d2;

You are copying a reference of a Dog object from the d2 variable to the d3 variable. You are not making a copy of the object.

Therefore, after the assignment, both d3 and d2 refer to the same Dog object. Therefore d3.age = 6; causes d2.age to be 6.