1

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.

IsteveI
  • 19
  • 4
  • 3
    `Cloneable` in Java is [awkward at best](https://stackoverflow.com/questions/4081858/about-java-cloneable), and generally people avoid it, in favor of explicit copy constructors. The general answer to questions involving `Cloneable` is "don't use `Cloneable`". – Silvio Mayolo Feb 21 '21 at 03:51

1 Answers1

1

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
    }
}

Ferry
  • 344
  • 3
  • 10
  • I did the deep copy of the object in the clone method. That is already implemented the deep copy so far. Or is the clone method not meant to be used like that? When you say Cloneable is legacy, u mean i have to implement it at my parent to implement it on my child or am i allowed to just implement it on my child. Because i dont need a clone method for my parent but i need one for my child? And i am only allowed to use Java.util + (regex, stream, function ) and Java.lang unfortunally. – IsteveI Feb 21 '21 at 11:48
  • no, legacy means it's old and should avoid that. if you already implemented the deep copy, it's better to use it on constructor – Ferry Feb 24 '21 at 15:04