For example, class A implements clone-able and its an abstract class, class B extends class A.
Suppose I need the clone method only in class B. Do I still need to use
A result = (A)super.clone();
in the clone
method?
For example, class A implements clone-able and its an abstract class, class B extends class A.
Suppose I need the clone method only in class B. Do I still need to use
A result = (A)super.clone();
in the clone
method?
No, you can just implement clone()
in B
as:
public B clone() {
try {
return (B) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
Note: the clone()
method is not defined in the Cloneable
interface. Cloneable
is just a so-called 'marker' interface. So A
doesn't need a clone()
method at all.
(You could also declare the method as throwing CNSE and let the caller deal with it. Note also that clone()
and Cloneable
are somewhat out of favor these days. Consider simply providing a copy constructor instead that takes a B
and copies the values of its fields.)