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 Cloneable interface 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 class
public 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 copy
Company BMW = (Company) Tesla.clone();
// setting values of BMW
BMW.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.java file.

  • 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.engineNumber to 4321.
  • Line 18: We change the cloned reference values BMW.car.name to Z4 (E89).
  • Line 23: We print the Tesla object values.
  • Line 25: We print BMW object values.

Free Resources