|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
How to clone objects
This example shows how to clone objects by implementing the Cloneable interface. Some classes implements the Cloneable interface by default but when creating custom classes the interface needs to be implemented explicitly. The class that implements the Cloneable interface (the Person class in the example) needs to have a method named clone() that returns an object. In the example we have chosen to create a new instance of Person and populate its properties with the same values as the object that the clone() method is called on. |
/** * Main.java * * @author www.javadb.com */ public class Main { /** * Creates and clones instances of Person class */ public void cloneObject() { Person person1 = new Person(); person1.setFirstName("Obi-Wan"); person1.setLastName("Kenobi"); Person person2 = (Person)person1.clone(); Person person3 = (Person)person2.clone(); System.out.println("Person 1: " + person1.getFirstName() + " " + person1.getLastName()); System.out.println("Person 2: " + person2.getFirstName() + " " + person2.getLastName()); System.out.println("Person 3: " + person3.getFirstName() + " " + person3.getLastName()); } /** * The Person class */ class Person implements Cloneable { private String firstName; private String lastName; public Object clone() { Person obj = new Person(); obj.setFirstName(this.firstName); obj.setLastName(this.lastName); return obj; } 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; } } /** * Starts the program * * @param args the command line arguments */ public static void main(String[] args) { new Main().cloneObject(); } } |
Since we chose to populate the cloned object with the same values of its variables as the object that the clone() method was call on, the output of the above example will look like this: |
Person 1: Obi-Wan Kenobi Person 2: Obi-Wan Kenobi Person 3: Obi-Wan Kenobi |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
