Skip to content

Conversation

dgruntz
Copy link
Contributor

@dgruntz dgruntz commented Nov 18, 2019

You mention in the code example how the protoype pattern can be implemented in Java with the help of Java cloning (i.e. with support of Object.clone()), but then you should also invoke Object.clone.

With the implementation

public Sheep clone() throws CloneNotSupportedException {
  return new Sheep(name);
}

it would not be possible (in general) to override clone() in a subclass (e.g. SpecialSheep), because invoking super.clone would return an object of the wrong type, and if we create a new instance of SpecialSheep it is not always possible to copy over the private fields.

This problem can be fixed by using the mechanism provided by Object.clone, i.e. by invoking super.clone(). This creates a shallow copy (which is just fine in this example as the type of the name field (String) is immutable.

@iluwatar
Copy link
Owner

Confirmed, typically super.clone() should be invoked in the clone method implementation.

@iluwatar
Copy link
Owner

We should change the description so that it reflects the example (there are no sheeps in the code).

@dgruntz
Copy link
Contributor Author

dgruntz commented Nov 19, 2019

Beyond the example you probably should also explain the difference between Java-Cloning (a clone implementation based on super-calls up to Object.clone) and Cloning using Copy-Constructors (where each non-abstract class defines a clone method of the form

public X clone() { return new X(this); }

and where each class (also abstract ones) provides a copy constructor which first invokes the copy constructor of the base class.

And then you should also explain the difference between deep and shallow copy.

@iluwatar iluwatar added this to the 1.23.0 milestone Nov 19, 2019
@iluwatar iluwatar merged commit a9c3df7 into iluwatar:master Nov 19, 2019
@iluwatar
Copy link
Owner

Thanks for the update @dgruntz.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants