Program to demonstrate how to Clone an Object in Java
Output of the program :
package com.hubberspot.example; //1. class should implement Cloneable interface public class Customer implements Cloneable { private int id; private String name; public String toString() { return "(id = " + id + ", name = " + name + ")"; } //2. class should override clone() method //3. will throw CloneNotSupportedException exception if // interface not implemented ... @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public static void main(String[] args) { Customer customer = new Customer(); customer.id = 5; customer.name = "magicman"; try { //4. calling clone() method to clone Customer Customer customerClone = (Customer) customer.clone(); System.out.println("Cloned Customer before changes = " + customerClone); customerClone.id = 10; customerClone.name = "jonty"; System.out.println("Cloned Customer after changes = " + customerClone); System.out.println("Original Customer = " + customer); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }
Output of the program :