Q
Q
qwead2017-12-27 10:51:02
Software design
qwead, 2017-12-27 10:51:02

Why is the ICloneable interface needed if there is a copy constructor?

What prevents the client from calling the copy constructor directly when creating a copy of an object? how is this code worse than this one?:
Circle copyOfCircle = new Circle(oldCircle);
Circle copyOfCircle = (Circle) oldCircle.Clone();

public class Circle implements ICloneable {
    public int radius;

    public Circle() {
    }

    public Circle(Circle target) {
         /* super(target); */
        if (target != null) {
            this.radius = target.radius;
        }
    }

    @Override
    public Object clone() {
        return new Circle(this);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-12-27
@qwead

The ICloneable interface is a marker interface that tells other program elements that objects of a class that implements this interface can be cloned.
The calling code may not know if this class has a copy constructor, and there is no doubt that there is a Clone() method for an IClonable instance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question