0

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?

Daniel
  • 2,355
  • 9
  • 23
  • 30
naor ohayon
  • 319
  • 2
  • 8
  • Possible duplicate of [Java clone() method](https://stackoverflow.com/questions/30078647/java-clone-method) –  May 20 '18 at 12:49

1 Answers1

0

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

David Conrad
  • 15,432
  • 2
  • 42
  • 54
  • thank you, so if i have some variables like int, string in A class, it will copy it as a deep cloning method? like it will create a new B object? – naor ohayon May 22 '18 at 13:19
  • @naor It will create a new B object and copy all the fields over, even fields declared in a superclass of B such as A, but as to a deep clone, if it contained, say, a list, the clone would get a copy of a reference to the list. So if you modify the list in the original (say, by adding an item), the change would appear in the clone as well. – David Conrad May 22 '18 at 13:41