Search code examples
javainheritancecloneableinterface-implementation

Java implementing interface Cloneable on a inheritance structure


I got the following Questions on my code:

public class Parent {
    ...
}

public class Child extends Parent implements Cloneable {
    ...
    @Override
    public Child clone() {
        return new Child() //deep copy
    }
}

Here are my questions:

  1. Following the java conventions; Do i need to implement Cloneable for the parent as well?
  2. Do i have to add throws CloneNotSupportedException to the clone() method or am i allowed to leave it byside? Cause i cant catch the Exception where i call clone().

Thanks for your help.

Edit: I went with copy constructors, cause they are much more easier to implement and dynamic.


Solution

  • Cloneable is legacy (old and weird and should avoid that for future development). It can't do deep copy and its effort not worth it to implement. You need to use 3rd party library like Jackson or Apache to do deep copy. or you can build your own deep copy method.

    if you're already implemented deep copy, it's better to use it on constructor.

    public class Child extends Parent {
        public Child(Child child){
            this.property = child.getProperty();
            // any copies
        }
    }