Possible Duplicate:
Why is the clone() method protected in java.lang.Object?
Here is my test code for checking the clone method working,
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());
}
}
Throws compilation error: clone() has protected access in java.lang.Object at obj1.clone()
- What I am doing wrong here?
- What is the reason behind clone() is protected?
Thanks
Edit along with Answer: 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,
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);
}
}
}
2. Reason for clone() method being protect: I found this from the book Core Java,
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.
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.
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.
Hope this is helpful to others