简体   繁体   中英

How do Java objects work?

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

maybe there is really only one object with two references?

Yes.

This code:

obj2 = obj1;

is a reference assignment. No objects get copied.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM