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... ?