class
Implementing Cloneable interface
In this example we shall show you how to implement the Cloneable interface. A class implements the Cloneable interface to indicate to the Object.clone()
method that it is legal for that method to make a field-for-field copy of instances of that class. To implement the Cloneable interface we have performed the following steps:
- We have created a class,
Employee
that implements the Cloneable interface and in its overridenclone()
method it calls the super classclone()
method and throws a CloneNotSupportedException, in case the object should not be cloned. - We create a new
Employee
object and print out its fields’ values.
Then we get a clone object of the object and print out its fields’ values, that are equal to the original object’s fields’ values,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; public class ClonableClass { public static void main(String[] args) { try { Employee e1 = new Employee("Dolly", 1000); System.out.println(e1); System.out.println("The employee's name is " + e1.getN()); System.out.println("The employees's pay is " + e1.getP()); Employee e1Clone = (Employee) e1.clone(); System.out.println(e1Clone); System.out.println("The clone's name is " + e1Clone.getN()); System.out.println("The clones's pay is " + e1Clone.getP()); } catch (CloneNotSupportedException cnse) { System.out.println("Clone not supported"); } } } class Employee implements Cloneable { String n; int pay; public Employee(String name, int salary) { this.n = name; this.pay = salary; } public Employee() { } public String getN() { return n; } public void setN(String name) { this.n = name; } public void setP(int pay) { this.pay = pay; } public int getP() { return this.pay; } @Override public Object clone() throws CloneNotSupportedException { try { return super.clone(); } catch (CloneNotSupportedException cnse) { System.out.println("CloneNotSupportedException thrown " + cnse); throw new CloneNotSupportedException(); } } }
Output:
methodoverloading.Employee@e9f784d
The employee's name is Dolly
The employees's pay is 1000
methodoverloading.Employee@7930ebb
The clone's name is Dolly
The clones's pay is 1000
This was an example of how to implement the Cloneable interface in Java.