Question

I observed clone is method of Object Class and Object is super class of every class. In every class i'm getting the clone as override method, suppose i create class with name A if I'm not override clone method at class A, and created an object for A I'm not getting the access of clone method in a object

What the concept i'm missing in oop

Was it helpful?

Solution

There are two issues: first, clone() is a protected method of Object, so it can only be called from within the subclass unless you override it and make it public. Second, unless your class implements Cloneable, calling clone() will throw a CloneNotSupportedException. The typical approach is:

class A implements Cloneable {
    public Object clone() {
         try {
             return super.clone();
         } catch (CloneNotSupportedException e) {
             throw new RuntimeException("Impossible exception!", e);
         }
    }
}

(You could eliminate the try/catch block and declare your clone() method to throw CloneNotSupportedException. The method would be simpler but all the calling code would have to deal with the exception.)

Since Java allows you to narrow the return type when overriding a method, you could redefine clone() to return an A, saving the calling code from having to cast:

class A implements Cloneable {
    public A clone() {
         try {
             return (A) super.clone();
         } catch (CloneNotSupportedException e) {
             throw new RuntimeException("Impossible exception!", e);
         }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top