0

Object class is having clone method for creating exactly duplicate objects. This method works for every class but why can't I create copy of object of Object class? Which Java concepts behind such behavior ?

I tried two different cases but it doesn't work. It gives compile time error : The method clone() from the type Object is not visible

Object o = new Object();
Object o2 = o.clone();

Object o = new Test(); // Some Test class
Object o2 = o.clone();
Saurabh Gadariya
  • 191
  • 6
  • 20
  • What is your use-case? – Piyush Mattoo Oct 21 '14 at 14:39
  • "it doesn't work" more detail please. What happend? – talex Oct 21 '14 at 14:39
  • it gives compile time error : The method clone() from the type Object is not visible – Saurabh Gadariya Oct 21 '14 at 14:42
  • [Java .clone() was a mistake and basically broken, don't use it, it leads to pain and suffering](http://stackoverflow.com/questions/1106102/clone-vs-copy-constructor-vs-factory-method/1106159#1106159) –  Oct 21 '14 at 14:50
  • Please note that this question is not a duplicate of the linked question, since the normal scope of protected methods does not apply to .clone() – nos Oct 22 '14 at 11:07

1 Answers1

6

Object.clone() has protected access (which is why you're getting your error), and thus cannot be called directly like this. You have to override clone() in your own class and make the class implement the Cloneable interface.

From the link below:

The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.

See here for more details.

Tetramputechture
  • 2,911
  • 2
  • 33
  • 48
  • every class extends Object class, so protected clone method should be visible – Saurabh Gadariya Oct 21 '14 at 14:49
  • Actually you can call .clone() on a non Object class without tht class implementing it, despite it being protected in java.lang.Object (doing so results in a runtime CloneNotSupportedException, unless you actually override .clone() and implement the Cloneable interface) .clone() in java is handled quite specially - the normal rules of visibility doesn't apply to sub classes. .clone() is also generally viewed as a misdesigned feature that shouldn't be used. – nos Oct 21 '14 at 14:52