What is the reason Object.clone () is protected

Possible duplicate:
Why is the clone () method protected in java.lang.Object?

Here is my test code to test the clone method,

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 a compilation error: clone () has secure access in java.lang.Object on obj1.clone ()

  • What am I doing wrong here?
  • What is the reason clone () is protected?

thanks

Edit along with the answer: Well, finally, I see that my test posting works when I implemented the Cloneable interface and redefined the clone method. It does not work with simply overriding the clone () method from the 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 protecting the clone () method: I found this from a Core Java book,

The clone method is a protected Object method, which means that your code cannot just call it. Only the Employee class can clone Employee objects.

There is a reason for this limitation. Think about how the Object class can implement a clone. He knows nothing about the object at all, so he can only make a field copy. If all data fields in the object are numbers or other basic types, copying the fields is normal.

But if the object contains links to subobjects, then copying the field gives you another link to the subobject, so the source and cloned objects still use some information.

Hope this will be helpful to others.

+8
java design clone
source share
1 answer

You must override the clone method in the Test class.

Why it is protected is discussed here , although there seems to be no consensus.

+2
source share

All Articles