What is the reason behind Object.clone() is protected
<p>Here is my test code for checking the clone method working,</p>

<pre><code>class Test{
  int a;
  public void setA(int value){
a = value;
  }
  public int getA(){
   return a;
  }
}
class TestClass{   
   public static void main(String args[]){
   Test obj1 = new Test();
   obj1.setA(100);
   Test obj2 = obj1.clone();
   System.out.println("obj1 A:"+obj1.getA()+" obj2 A:"+obj2.getA());
   obj2.setA(9999);
   System.out.println("obj1 A:"+obj1.getA()+" obj2 A:"+obj2.getA());
 }
}
</code></pre>

<p>Throws compilation error: clone() has protected access in java.lang.Object at obj1.clone()</p>

<ol>
<li>What I am doing wrong here?</li>
<li>What is the reason behind clone() is protected?</li>
</ol>

<p>Thanks</p>

<p><strong>Edit along with Answer:</strong> Well at last I see my test harness is working when I implemented the Cloneable interface and overriden the clone method. It's not working with just overriding the clone() method from Object class. Here is the modified code,</p>

<pre><code>class Test implements Cloneable{
 int a;
 public void setA(int value){
a = value;
 }
 public int getA(){
return a;
 }
@Override
protected Test clone() throws CloneNotSupportedException{    
  return(Test) super.clone();  
  }   
}
class TestClass{   
  public static void main(String args[]){
     Test obj1 = new Test();
   obj1.setA(100);
   try{
     Test obj2 = (Test)obj1.clone();
     System.out.println("obj1 A:"+obj1.getA()+" obj2 A:"+obj2.getA());
     obj2.setA(9999);
     System.out.println("obj1 A:"+obj1.getA()+" obj2 A:"+obj2.getA());       
   }catch(Exception e){
     System.out.println("ERror"+e);
     }         
    }
  }
</code></pre>

<p>2. Reason for clone() method being protect: I found this from the book Core Java,</p>

<p>The clone method is a protected method of Object, which means that your code cannot simply call it. Only the Employee class can clone Employee objects.</p>

<p>There is a reason for this restriction. Think about the way in which the Object class can implement clone. It knows nothing about the object at all, so it can make only a field-byfield copy. If all data fields in the object are numbers or other basic types, copying the fields is just fine.</p>

<p>But if the object contains references to subobjects, then copying the field gives you another reference to the subobject, so the original and the cloned objects still share some information.</p>

<p>Hope this is helpful to others</p>
