When i implement Cloneable
in a class, say class AA
,
class AA
is cloneable-- i can invoke clone()
on an object of it
without getting a CloneNotSupportedException
. i can do this
without overriding clone()
(although it is recommended in order to keep the object independent from its clone).
When a class is Cloneable
, so are its descendants.
In the following code,
class ZZ {protected void mm(){System.out.println("+++");}}
class AA extends ZZ implements Cloneable {
// ...
protected Object clone () throws CloneNotSupportedException {return super.clone();}
AA cloneMe() throws CloneNotSupportedException { return (AA)clone(); }
}
class C extends AA {
public static void main(String[] args) throws CloneNotSupportedException {
C c = new C();
AA a = new AA();
AA a22 = (AA)(c.clone());
AA a3 = a.cloneMe();
C c2 = (C)c.clone();
AA a21 = (AA)a.clone();
a.mm();
}
}
i'm getting a checked error that
clone() has protected access in Object
to the line
AA a21 = (AA)a.clone();
when i comment the implementation of clone()
in AA
, i.e., the line
// protected Object clone () throws CloneNotSupportedException {return super.clone();}
Since AA
is cloneable, i should be able to clone an instance of it without implementing clone()
in AA
itself. AA
is inheriting clone()
from Object
.
So - how come this error???
TIA.
//=======================================
EDIT:
I have the same issue with the code above except class ZZ
which is the following code:
class AA implements Cloneable {
// ...
// protected Object clone () throws CloneNotSupportedException {return super.clone();}
AA cloneMe() throws CloneNotSupportedException { return (AA)clone(); }
}
class C extends AA {
public static void main(String[] args) throws CloneNotSupportedException {
C c = new C();
AA a = new AA();
AA a22 = (AA)(c.clone());
AA a3 = a.cloneMe();
C c2 = (C)c.clone();
AA a21 = (AA)a.clone();
}
}
class ZZ
was there to show that the invocation of a protected
method by a "grandchild" doesn't give the same error as the one by an invocation of clone()
in a similar way.
//===============================================
EDIT-2:
The answer in super.clone() operation not works in Derived Class says
"Clone is one of the early designs in java and it has flaws".
this seems to be the only explanation. looking for further verification on this.
i've looked into this before and without success-- some more on the native methods than their explanations in the Java docs. Still-- is there any more to the internals of clone()
--
how it is implemented, how it clones the members etc as well as how it is "managing" this out-of-the-ordinary access privilege? and under the circumstances??