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.
Object clone()
It does not accept any argument value.
Object
: A clone of this.
instance or object.
This method also throws a CloneNotSupportedException
exception. This means the thread can not be perfectly cloned.
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);}}
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.
clone()
method to the clone Tesla object to BMW fields, name, and total.BMW.car.engineNumber
to 4321.BMW.car.name
to Z4 (E89).