Java Object clone Method Example

In this example, we will demonstrate the usage of java.lang.Object.clone() method with an example.

Object clone() Method Examples

The clone() method creates and returns a copy of this object.

1. Simple Object clone() Method Example

This example shows the usage of the clone() method:
public class ObjectClass {
 
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date.toString());
        Date date2 = (Date) date.clone();
        System.out.println(date2.toString());
    }
}
Output:
Tue Sep 04 14:15:00 IST 2018
Tue Sep 04 14:15:00 IST 2018

2. Object clone() Method Example using Closable interface

In this example, we are using the Closable interface and clone() method together.
First, create a Person class which implements a Closable interface.
public class Person implements Cloneable {
     private String firstName;
     private String lastName;

     public String getFirstName() {
         return firstName;
     }

     public void setFirstName(String firstName) {
         this.firstName = firstName;
     }

     public String getLastName() {
         return lastName;
     }

     public void setLastName(String lastName) {
         this.lastName = lastName;
     }

    @Override
    public Object clone() throws CloneNotSupportedException {
        Person person = (Person) super.clone();
        return person;
    }

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    }
}
Now, test above Person.clone() method using main() method:
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        person.setFirstName("Ramesh");
        person.setLastName("Fadatare");

        System.out.println(person.toString());

        Person person2 = (Person) person.clone();

        System.out.println(person2.toString());
    }
Output:
Person [firstName=Ramesh, lastName=Fadatare]
Person [firstName=Ramesh, lastName=Fadatare]
Note that we have to override the clone() method from the Object class and made a call to Object clone() method using super.clone().
@Override
public Object clone() throws CloneNotSupportedException {
       Person person = (Person) super.clone();
       return person;
}

Reference

https://www.javaguides.net/2018/09/object-class-methods-in-java-with-examples.html


Comments