title: Java - Having the same reference in multiple class
body: <p>how to make references to the same instance in multiple objects?</p>
  
  <p>Let say I have Class A :</p>
  
  <pre><code>Class A{
      public A relative = null;
      public int number = 0;
  }
  </code></pre>
  
  <p>and I will create multiple A and those A's relative will be a reference to one of those A.</p>
  
  <p>For example:
  Let's create four A, so now we have A1, A2, A3, A4.</p>
  
  <p>And the following map will shows (Left Hand Side)'s relative is making reference to (Right Hand Side)</p>
  
  <pre><code>A1 =&gt; null,
  A2 =&gt; A1,
  A3 =&gt; A1,
  A4 =&gt; A2
  </code></pre>
  
  <p>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)</p>
  
  <p>So, here are what I have tried:</p>
  
  <ol>
  <li><p>Using setter:</p>
  
  <pre><code>public void relateTo(A relative){
      this.relative = relative;
  }
  </code></pre>
  
  <p>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.</p></li>
  <li><p>Public the variable and direct access it</p>
  
  <pre><code>A2.relative = A1;
  </code></pre>
  
  <p>But nope, this doesn't works.</p></li>
  </ol>
  
  <p>I have no idea how to achieve this, any ideas?</p>