Java Reference
In-Depth Information
Listing 7-12. A Test Class to Test Deep Cloning of Objects
// DeepCloneTest.java
package com.jdojo.object;
public class DeepCloneTest {
public static void main(String[] args) {
DeepClone sc = new DeepClone(100.00);
DeepClone scClone = (DeepClone)sc.clone();
// Print the value in original and clone
System.out.println("Original:" + sc.getValue());
System.out.println("Clone :" + scClone.getValue());
// Change the value in original and it will not change the value
// for clone because we have done deep cloning
sc.setValue(200.00);
// Print the value in original and clone
System.out.println("Original:" + sc.getValue());
System.out.println("Clone :" + scClone.getValue());
}
}
Original:100.0
Clone :100.0
Original:200.0
Clone :100.0
Using the clone() method of the Object class is not the only way to make a clone of an object. You can use
other methods to clone an object. You may provide a copy constructor, which accepts an object of the same class and
creates a clone of that object. You may provide a factory method in your class, which may accept an object and returns
its clone. another way to clone an object is to serialize it and then deserialized it. serializing and deserializing objects is
covered in Chapter 7 in Beginning Java Language Features .
Tip
Finalizing an Object
Sometimes an object uses resources that need to be released when the object is destroyed. Java provides you with a
way to perform resource release or some other type of cleanup, when an object is about to be destroyed. In Java, you
create objects, but you cannot destroy objects. The JVM runs a low priority special task called garbage collector to
destroy all objects that are no longer referenced. The garbage collector gives you a chance to execute your cleanup
code before an object is destroyed.
The Object class has a finalize() method, which is declared as follows:
protected void finalize() throws Throwable { }
 
 
Search WWH ::




Custom Search