Easy Tutorial
❮ Exception Finally Number Random ❯

Java Object clone() Method

Java Object Class


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

The clone method performs a shallow copy, where the object's properties that reference other objects only copy the reference addresses, rather than allocating new memory for the referenced objects. In contrast, a deep copy would also recreate the referenced objects.

Syntax

object.clone()

Parameters

Return Value

Returns a copy of the object.

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

Example

The following example creates an obj1 object, then copies obj1 to obj2, and prints the values of the variables using obj2:

Example

class tutorialproTest implements Cloneable {

    // Declare variables
    String name;
    int likes;

    public static void main(String[] args) {

        // Create object
        tutorialproTest obj1 = new tutorialproTest();

        // Initialize variables
        obj1.name = "tutorialpro";
        obj1.likes = 111;

        // Print output
        System.out.println(obj1.name); // tutorialpro
        System.out.println(obj1.likes); // 111

        try {

            // Create a copy of obj1
            tutorialproTest obj2 = (tutorialproTest) obj1.clone();

            // Print variables using obj2
            System.out.println(obj2.name); // tutorialpro
            System.out.println(obj2.likes); // 111
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}

The above program execution results are:

tutorialpro
111
tutorialpro
111

Java Object Class

❮ Exception Finally Number Random ❯