Search code examples
javaclone

what the syntax for clone method if the subclass extends abstract class?


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?


Solution

  • 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.)