Reputation: 288
Why does this work the way it does... (counter-intuitively for me)
Test.java:
public class Test {
public TestObject obj1;
public TestObject obj2;
public Test() {
obj1 = new TestObject();
obj1.setInt(1);
obj2 = obj1;
System.out.println("Should be the same: " + obj1.getInt() + ", " + obj2.getInt());
obj1.setInt(2);
System.out.println("Should be different? (2, 1): " + obj1.getInt() + ", " + obj2.getInt());
obj2.setInt(3);
System.out.println("Should be different? (2, 3): " + obj1.getInt() + ", " + obj2.getInt());
}
public static void main(String[] args) {
new Test();
}
}
TestObject.java
public class TestObject {
int integer;
public void setInt(int n) {
integer = n;
}
public int getInt() {
return integer;
}
}
This, surprisingly results in the "both objects" changing so that "int integer" is the same.
Logically (if my logic makes any sense), I would assume that setting one object to be equal to another would be a one-time thing, and that any change in either one of the objects would not automatically change the other. Is there something I am missing, such as maybe there is really only one object with two references? Or something... ?
Upvotes: 1
Views: 555
Reputation: 2823
When you typed obj2 = obj1; you basically said that both pointers for obj2 and obj1 should point to the same memory address, therefore, to the same object. You should type:
...
obj1 = new TestObject();
obj1.setInt(1);
obj2 = new TestObject();
...
Upvotes: 0
Reputation: 68715
Both the objects are pointing to the same memory object as you have done the assignment:
obj2 = obj1;
Not matter what change you do using either of the references, the change will be done to the same memory object.
Upvotes: 0
Reputation: 272467
maybe there is really only one object with two references?
Yes.
This code:
obj2 = obj1;
is a reference assignment. No objects get copied.
Upvotes: 3
Reputation: 120178
Both obj1
and obj2
are references to the same object after you do the assignment. So after
obj2 = obj1;
both references point to the same object; all results should match. If you want to copy, you can do something like
obj2 = new TestObject(obj1.getInt());
or create a new constructor that takes an instance and creates a copy (a bit nicer API).
Upvotes: 2