1

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

4 Answers 4

3

maybe there is really only one object with two references?

Yes.

This code:

obj2 = obj1;

is a reference assignment. No objects get copied.

Sign up to request clarification or add additional context in comments.

1 Comment

"No objects get copied".. that makes sense then. How would I make it so that an object DOES get copied? Do I have to do it manually and create a second object?
2

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

Comments

0

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.

Comments

0

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();
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.