title: Encapsulation for Reference Variables?
body: <p>It may be a common question but I couldn't find nice explanation for it. I am trying to understand the <code>encapsulation of reference variables</code> in <code>Java</code>.<br><strong>In the below code:</strong></p>
  
  <pre><code>class Special {
      private StringBuilder s = new StringBuilder("bob"); 
      StringBuilder getName() { return s; }
      void printName() { System.out.println(s); } 
  }
  public class TestSpecial {
      public static void main (String[] args ) {
      Special sp = new Special();
      StringBuilder s2 = sp.getName();
      s2.append("fred");
      sp.printName();
      }
  }
  </code></pre>
  
  <p><strong>Output:</strong> bobfred</p>
  
  <p>At first I thought making our field <code>private</code> and providing a <code>getter</code> method, it's a good encapsulation technique. But when I took closer look on it, I saw that when I invoke <code>getName()</code>, I do in fact return a copy, just like Java always does. But, I am not returning a copy of the <code>StringBuilder</code> object. I am returning a copy of the reference variable that point to the one and only <code>StringBuilder</code> object. So, at the point that <code>getName()</code> returns, I have one <code>StringBuilder</code> object and two reference variables pointing to it <strong>( s and s2).</strong></p>
  
  <p><strong>What are the techniques to make it well encapsulated?? A good explanation with code example expected :) . Thanks in advance.</strong> </p>