CSC 216/s08/feign ignorance
Cloning and the Object Superclass
A group exercise to help clarify the ambiguities related to cloning objects in Java.
The problem
Cloning objects in Java is not as straightforward as one might expect. Every object inherits a set of standard methods, including the clone() method from the Object superclass, but by default this method is protected. This prevents instances of classes outside of the object's package from cloning that object (unless it is a subclass of that object). By default, when a class implements the Cloneable interface, a call to the clone() method creates a shallow copy of that object, which allocates memory for a new instance and copies the memory allocated for the current object. This is ideal for simple objects whose local variables only include primitive types, but if an object includes local variables that are references to other objects, then a deep copy may be preferred. Choosing between implementing a deep copy or shallow copy implementation of the clone() method depends upon the goals of the project and the overall design.
Participants and props
3 Participants are required for this activity. A large class may be divided into groups of three, or three volunteers may demonstrate for the rest of the class.
- 1 Student shall act as the prototype Person A.
- 1 Student shall be (null) until they become Person B, a clone of Person A.
- 1 Student to direct the operation and to ask questions.
Materials required:
- 2 Cellphones (or other ubiquitous semi-identical objects)
- 3 Index cards, formatted as shown in the figure below:
The script
Initially, one student shall play the role of Person A, and should write their name and age upon Card A, and hold onto the card, as well as one of the cellphones. A second student shall hold the (null) card (to represent a non-existent Person). The third student shall be the Conductor and will hold the Person B card and the additional cellphone.
Shallow Copy Begin by having the Conductor assist in carrying out a shallow copy clone() of Person A.
- Ask Person A their name, age and to exhibit their cellphone.
- Clone Person A by exchanging the Person B card with the (null) card held by the second student.
- Person B should write their new name and age on the Person B card.
- Ask Person A and Person B their name and age independently, and to exhibit their cellphone. (At this time the conductor should possess the (null) card and one of the cell phone, and both students should attempt to exhibit Person A's cellphone as their own).
- What would happen if Person A changes the number associated with their cellphone? How does this affect Person B?
Deep Copy
References
- Learning Java - Chapter 8 : Java : Supplements
- You can insert Cloneability at any level of inheritance : Clone « Language Basics « Java