Java Object clone() Method

Java String类Java Object Class


The Object clone() method is used to create and return a copy of an object.

The clone method is a shallow copy. For objects referenced by properties within the object, only the reference address is copied, and the referenced object is not reallocated memory. In contrast, a deep copy recreates the referenced objects as well.

Syntax

object.clone()

Parameters

  • None 。

Return Value

Returns a copy of an object.

Since Object itself does not implement the Cloneable interface, calling the clone method without overriding it will throw a CloneNotSupportedException.

Example

The following example creates the obj1 object, then copies obj1 to obj2, and outputs the variable values through obj2:

Example

class ExampleTest implements Cloneable { //Declare variables String name; int likes; public static void main(String[] args) { //Create object ExampleTest obj1 = new ExampleTest(); //Initialize variables obj1.name = "Example"; obj1.likes = 111; //Print output System.out.println(obj1.name); // Example System.out.println(obj1.likes); // 111 try { //Create a copy of obj1 ExampleTest obj2 = (ExampleTest) obj1.clone(); //Use obj2 to output variables System.out.println(obj2.name); // Example System.out.println(obj2.likes); // 111 } catch (Exception e) { System.out.println(e); } } }

The above program produces the following result:

Example
111
Example
111

Java String类Java Object Class

Other Extensions