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 clonePerson
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 theclone()
method to get its clone, then use theclone()
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.