i tried the following code for cloning the object. while compiling it shows clone is protected and cannot be accessed, but i had extended Object class, hence the clone method will be public to my class . please explain me the reason.
class storeDate extends Object {
public static void main(String[] args)
{
storeDate d = new storeDate();
Object o = (storeDate)d;
o.clone():
}
}
while compilation i get this error
clone() has protected access in java.lang.Object
kkk.clone();
The key thing here is which package the classes belongs to.
This is explained in JLS paragraph 6.6.2:
Examples:
This does not compile:
FILE pkg1/A.java (corresponds to the Object class in your question)
FILE pkg2/B.java (corresponds to storeDate in your question)
javacoutputs the following:(which is similar to what you have: clone() has protected access in java.lang.Object kkk.clone();)
Simply moving
Bto thepkg1package solves it.That is, this does compile:
FILE pkg1/A.java (unchanged)
FILE pkg1/B.java (moved from pkg2 to pkg1)
So, what would have been required for you to be able to do something like
new Object().clone()? Well, you would have to belong to thejava.langpackage (which in turn, however results in aSecurityException: Prohibited package name: java.lang).