Hello,
Here is the code:
import java.util.Stack;
public class Clone implements Cloneable {
Stack<Object> stack = new Stack<Object>();
public Clone() {
}
public Object clone() throws CloneNotSupportedException {
Clone rv = (Clone) super.clone();
rv.stack = (Stack<Object>) stack.clone();
return rv;
}
public static void main (String[] args) throws
CloneNotSupportedException {
System.out.println("hello world!");
Clone a = new Clone();
Clone b = (Clone) a.clone();
}
}
It seems like the explicit cast should prevent the warning, but it does
not. Without the explicit cast, the code generates a compile error. I
can live with warnings, but it sure seems like what I am trying to do
is valid. Did the language designers (1.5) miss this on accident, or
is there something simple that I am missing? Does anybody have any
thoughts?
Thanks,
Randall
hiwa - 23 Apr 2006 07:31 GMT
Since Java generics is based on the 'erasure' mechanism,
this cast and getting a warning is always unavoidable.
Sun gives us a small solace called SuppressWarnings
annotation.
For your (Clone) casting for clone() return value, I personally
think Java cloning has failed to keep step with generics and
it is a major bug.
Piotr Kobzda - 23 Apr 2006 07:57 GMT
> It seems like the explicit cast should prevent the warning, but it does
> not. Without the explicit cast, the code generates a compile error. I
> can live with warnings, but it sure seems like what I am trying to do
> is valid. Did the language designers (1.5) miss this on accident, or
> is there something simple that I am missing? Does anybody have any
> thoughts?
Covariant return types introduced in Java 5 allows you to write a method
whose return type is a subclass of the type returned by the method with
the same signature in the superclass.
Thus your clone() method would be declared as:
public Clone clone() { ...
Which allows for usage like:
Clone a = new Clone();
Clone b = a.clone();
BTW -- Declaring CloneNotSupportedException with a custom clone() method
when a class implements Cloneable is impractical /will never happen for
such a class/, and should be handled in that method.
Regards,
piotr
hiwa - 23 Apr 2006 09:23 GMT
> Covariant return types introduced in Java 5 allows you to write a method
> whose return type is a subclass of the type returned by the method with
[quoted text clipped - 8 lines]
> Clone a = new Clone();
> Clone b = a.clone();
It works. Thanks. But I can't find any article(s) on
covariant return type in the JDK 1.5 standard
documentation set. I've found this article on
bugdatabase:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6349937