title: How to do deep copy for the below class in Java
body: <p>Look at this class. I get the below class from a great book, &quot;On Java&quot;, but how can I deep copy the class?</p>
  <pre><code> public class Snake implements Cloneable {
      private Snake next;
      private char c;
  
      public Snake(int i, char x) {
          c = x;
          if(--i &gt; 0)
              next = new Snake(i, (char)(x + 1));
      }
  
      public void increment() {
          c++;
          if(next != null)
              next.increment();
      }
  
      @Override public String toString() {
          String s = &quot;:&quot; + c;
          if(next != null)
              s += next.toString();
          return s;
      }
  
      @Override public Snake clone() {
          try {
             Snake snake = (Snake) super.clone();
  
              return snake;
  
          } catch(CloneNotSupportedException e) {
              throw new RuntimeException(e);
          }
      }
  
      public static void main(String[] args) {
          Snake s = new Snake(5, 'a');
          System.out.println(&quot;s = &quot; + s);
          Snake s2 = s.clone();
          System.out.println(&quot;s2 = &quot; + s2);
          s.increment();
          System.out.println(
                  &quot;after s.increment, s = &quot; + s);
          System.out.println(
                  &quot;after s.increment, s2 = &quot; + s2);
  
      }
  }
  </code></pre>