0

how to make references to the same instance in multiple objects?

Let say I have Class A :

Class A{
    public A relative = null;
    public int number = 0;
}

and I will create multiple A and those A's relative will be a reference to one of those A.

For example: Let's create four A, so now we have A1, A2, A3, A4.

And the following map will shows (Left Hand Side)'s relative is making reference to (Right Hand Side)

A1 => null,
A2 => A1,
A3 => A1,
A4 => A2

What I want to achieve is: When I modified A1 by (A2.relative.number = 1), and will also "apply" to A3's relative (Which supposed to be a reference to the same instance A1)

So, here are what I have tried:

  1. Using setter:

    public void relateTo(A relative){
        this.relative = relative;
    }
    

    This doesn't works, since Java is passing reference by value. Where the relative inside the scope of this method is just a copy. So whenever I make any changes to it from outside, it doesn't make changes to this.

  2. Public the variable and direct access it

    A2.relative = A1;
    

    But nope, this doesn't works.

I have no idea how to achieve this, any ideas?

1
  • 1
    It would really help if you'd show a short but complete example. If A2 and A3 both refer to A1, then it really should be fine. Commented Dec 6, 2013 at 15:33

2 Answers 2

3

When I modified A1 by (A2.relative.number = 1), and will also "apply" to A3's relative (Which supposed to be a reference to the same instance A1)

This principle is simlpy achieved by making two references point at the same object

Example

A a1 = new A();
A a2 = new A();
A a3 = new A();

a2.relative = a1;
a3.relative = a1;
// Now both a2 relative and a3 relative point to the same A object.

Now if I make a change to a2 relative, say

a2.relative.number = 2;

Then a3 relative will have also changed.

Why?

This is because, when you declare an object, you're actually handling the pointer to that object; not the object itself. What the code above does, is create one relative, and make two classes point to it.

enter image description here

Observe my beautiful artwork

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

Comments

1

This doesn't works, since Java is passing reference by value. Where the relative inside the scope of this method is just a copy. So whenever I make any changes to it from outside, it doesn't make changes to this.

Did you try this?

Java passes object references by value; any changes made to those references affect the object in question. Similar to passing pointers in other languages.

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.