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. } }
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.
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.
6.1. Apache Commons Lang has SerializationUtils#clone, which performs a deep copy when all classes in the object graph implement the Serializable interface.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With