KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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
Tags (comma-separated)
Save Edits
Cancel