Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method clone() from object is not visible?

Question:

package GoodQuestions; public class MyClass {       MyClass() throws CloneNotSupportedException {         try {             throw new CloneNotSupportedException();         } catch(Exception e) {             e.printStackTrace();         }     }         public static void main(String[] args) {             try {             MyClass  obj = new MyClass();             MyClass obj3 = (MyClass)obj.clone();                     } catch (CloneNotSupportedException e) {             e.printStackTrace();         }     } } 

Here class 'MyClass' can able to clone its own object by calling the clone method in 'Object' class. When I try to clone the of this class('MyClass') in another class('TestSingleTon') in the same package 'GoodQuestions' it is throwing the following compile time error.

'The method clone() from the type Object is not visible'

So here is the code it throwing the above error?

package GoodQuestions; public class TestSingleTon {     public static void main(String[] args) {         MyClass  obj = new MyClass();         MyClass obj3 = obj.clone(); ---> here is the compile error.     } } 
like image 548
sekhar Avatar asked Feb 25 '11 10:02

sekhar


People also ask

What is clone () method?

clone() method in Java Java Programming Java8Object Oriented Programming. Java provides an assignment operator to copy the values but no operator to copy the object. Object class has a clone method which can be used to copy the values of an object without any side-effect.

Can we see the clone method without overriding it in any class?

Clone is Protected method in Object class so it is accessible to you inside class. About access- When a method is protected, it can only be accessed by the class itself, subclasses of the class, or classes in the same package as the class.

Does clone () make a deep copy?

6.1. Apache Commons Lang has SerializationUtils#clone, which performs a deep copy when all classes in the object graph implement the Serializable interface.


2 Answers

clone() has protected access. Add this in MyClass

public Object clone(){       try{           return super.clone();       }catch(Exception e){          return null;      } } 

Also Change to public class MyClass implements Cloneable

like image 80
EsotericMe Avatar answered Sep 20 '22 07:09

EsotericMe


This error occurs because in Object class clone() method is protected. So you have to override clone() method in respective class. Eg. Add below code in MyClass

@Override protected Object clone() throws CloneNotSupportedException {      return super.clone(); } 

Also implement Cloneable interface. Eg. public class MyClass implements Cloneable

like image 38
Prashant K Avatar answered Sep 18 '22 07:09

Prashant K