简体   繁体   中英

Java: Multiple representations of the same object

I have a User.class like this:

public class User {
    private HashSet<Client> clients;
    ...
    public void addClient(Client c) {
        c.setParentUser(this);
        clients.add(c);
}

And the Client class:

public class Client {
    private User parentUser;
    public void setParentUser(User u) {
        parentUser = u;
    }
    ...
}

My question is, at the c.setParentUser(this) , my intention is to have a "pointer" to the user that holds the client.

So my question is: will c.setParentUser(this) just store a reference in the Client, or will it create a new object that is exactly the same as this (User)?

It stores a reference, like a C/C++ pointer. The variable parentUser references the same object as this (in the User class).

If you want to make a copy, you need to do so explicitly.

It's a reference , not a copy.

Everything other than primitives (int, double etc.) in Java is a reference. If I write:

String s = "abc";

then s is actually a reference to a String , strictly speaking. Not a String per se . For objects (not primitives) you have to explicitly write a copy constructor to create a copy. If I pass s to a method, the reference is copied by value, but it still refers to the original String object.

Client.parentUser will contain a copy of the reference passed into the setParentUser method.

Just be aware that if perform something along the lines of:

public void setParentUser(User u) {
    parentUser = u;
    u = new User();
}

The reference will have been changed and the reference to the original User passed into the function will not be changed if you modify the fields of the Client.parentUser .

c.setParentUser(this);

这是“ Has A关系”,它仅包含User对象的对象引用。

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