What is the Thread clone() function in java?
The clone() method from the java.lang.Thread class makes an exact copy of a thread. Object cloning refers to making an exact copy of that object in memory by cloning all its fields.
The
Cloneableinterface is also implemented by this Thread class.
Syntax
Object clone()
Parameters
It does not accept any argument value.
Return value
Object: A clone of this. instance or object.
Exception
This method also throws a CloneNotSupportedException exception. This means the thread can not be perfectly cloned.
Code
Main.java
Company.java
vehicle.java
import java.util.*;// Driver Main classpublic class Main {public static void main(String args[]) throws CloneNotSupportedException {Company Tesla = new Company();Tesla.total = 1;Tesla.car.name = "Model S";Tesla.car.engineNumber = 1234;System.out.println("Car1: Before Cloned() called");System.out.println(Tesla.total + " " + Tesla.car.engineNumber+ " " + Tesla.car.name);// calling clone() method// to make shallow copyCompany BMW = (Company) Tesla.clone();// setting values of BMWBMW.car.engineNumber = 4321;BMW.car.name = "Z4 (E89)";// Change in object type field will be// reflected in both t2 and t1(shallow copy)System.out.println();System.out.println("After Cloned() called");System.out.println("Car1: "+ Tesla.total + " " + Tesla.car.engineNumber+ " " + Tesla.car.name);System.out.println("Car2: "+ BMW.total + " " + BMW.car.engineNumber+ " " + BMW.car.name);}}
Explanation
In the code snippet above, we have three classes named Main.java, Company.java, and Vehicle.java.
The following line numbers refer to the
Main.javafile.
- Line 6: We instantiate the Company class as a Tesla object.
- Line 15: We call the
clone()method to the clone Tesla object to BMW fields, name, and total. - Line 17: We now change the cloned reference values
BMW.car.engineNumberto 4321. - Line 18: We change the cloned reference values
BMW.car.nameto Z4 (E89). - Line 23: We print the Tesla object values.
- Line 25: We print BMW object values.