Cloning
- 2 types of clones of an object
- Shallow copy: Partial duplicate of an object
- Deep copy: Complete duplicate of object.
- Shallow copy
- The clone’s primitive fields are new variables given the same value as in original Object.
- But the clone’s Object fields are references to the same object in the original field.
- All shallow copies and the original object are linked through their object fields. They’re always the same.
- Changes made to clone’s object fields are mirrored in the original (and all clones).
Object.clone()
in Java is a shallow copy
- Deep copy:
- Object fields are entirely new objects.
- Changes made to a cloned object’s object fields are not mirrored in the original.