Question: clone() not accessible from outside on a Cloneable instance - why?
Answer: clone() is defined as a protected method in the Object class. When we implement the marker interface Cloneable then only that class gets the license to call the default Object.clone() method i.e., only the methods of that implementing class can call the inherited clone() method. The Object.clone() method carries a protected access, so even if we want the default clone() (Shallow Copy) to be called from outside, we need to override the clone() method in the class implementing Cleanble and promote the access specifier of the overriden clone() method to 'public'.
class SampleA implements Cloneable{
...
public Object clone(){
super.clone();
}
...
}
public class CloningDemo {
public static void main(String [] args){
...
SampleA sampleA = new SampleA();
sampleACloned = sampleA.clone();
...
}
}
'sampleACloned = sampleA.clone();' - this statement is valid in this case as we have overriden the clone() method with a 'public' access specifier in the class SampleA. Otherwise, it'll throw a compile-time error "method clone() has protected access in class java.lang.Object'.
No comments:
Post a Comment