Q: What is the Clone () function for?
A: Clone () can produce an identical class and return it to the caller.
Q: How the Clone () works.
A: Object implements Clone () as a local method, which means that its code is stored in a local library. When the code executes, it checks to see if the class (or parent Class) of the calling object implements the Java.lang.Cloneable interface (the object class does not implement Cloneable). If this interface is not implemented, clone () throws a check exception ()--java.lang.clonenotsupportedexception, and if this interface is implemented, clone () creates a new object. The contents of the original object are copied to the new object, and the reference to the new object is finally returned.
Q: How to Invoke Clone () to clone an object.
A: Use the object you want to clone to invoke Clone (), and assign the returned object from the object class to the class to which the cloned object belongs, and to the object's reference. Here is an example in Listing 3. Code Listing 3: Cloning an object
1 2 3 4 5 6 7 8 9 10 11 |
public class Clonedemo implements cloneable {int x; public static void Main (string[] args) throws Clonenotsupportedexception {Clonedemo cd = new Clonedemo (); Cd.x = 5; System.out.printf ("cd.x =%d%n", cd.x); Clonedemo CD2 = (Clonedemo) cd.clone (); System.out.printf ("cd2.x =%d%n", cd2.x); } } |
Code Listing 3 declares a Clonedemo class that inherits the Cloneable interface. This interface must be implemented, otherwise, calling the object's clone () will cause an exception clonenotsupportedexception to be thrown.
Clonedemo declares an int variable x and the main function main () to demonstrate this class. where the main () declaration may throw a clonenotsupportedexception exception out.
Main () instantiates the Clonedemo and initializes the value of X to 5. The value of x is then output, followed by the invocation of Clone (), which returns the cloned object back to Clonedemo. Finally, the value of the cloned X is exported.
Compile Code Listing 3 (Javac Clonedemo.java) and then run (