class

Clonable Object example

With this example we are going to demonstrate how to create a cloneable object of a class. In short, to create a cloneable object of a class, we have created a class that implements the Cloneable interface, so that it can use the clone() method to create cloneable objects, as described in the following steps:

  • We have created a class Person, that implements the Cloneable interface. It has two String fields.
  • The class overrides the clone() method of Object, where it creates a clone Person object, sets the fields of the clone object to the ones of the original one, and returns the clone object. It also has getters and setters for its fields. 
  • We create a new Person object and then use the clone() method to get its clone, then use the clone() method to get a clone of the clone.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;


public class ClonableClass {

    public static void main(String[] args) {

  Person person1 = new Person();


  person1.setFN("F");

  person1.setLN("L");


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

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


  System.out.println("Person 1: " + person1.getFN() + " " + person1.getLN());

  System.out.println("Person 2: " + person2.getFN() + " " + person2.getLN());

  System.out.println("Person 3: " + person3.getFN() + " " + person3.getLN());
    }
}

class Person implements Cloneable {

    private String fn;
    private String ln;

    @Override
    public Object clone() {


  Person object = new Person();

  object.setFN(this.fn);

  object.setLN(this.ln);


  return object;
    }

    public String getFN() {

  return fn;
    }

    public void setFN(String firstName) {

  this.fn = firstName;
    }

    public String getLN() {

  return ln;
    }

    public void setLN(String lastName) {

  this.ln = lastName;
    }
}

Output:

Person 1: F L
Person 2: F L
Person 3: F L

  
This was an example of how to create a cloneable object of a class in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button