clone means to copy and create exact same replica of the original object.
java.lang.Cloneable
interface provides a clone
method. when clone
is called via an object, the JVM creates an new object
of the same type and copies all the values of the old object into the newly created object.
package org.wesome.dsalgo.design.pattern;
public class Apple implements Cloneable {
String name = "McIntosh";
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public Apple() {
System.out.println("Apple default constructor");
}
public static void main(String[] args) {
try {
Apple apple = new Apple();
System.out.println("apple = " + apple);
System.out.println("apple name = " + apple.name);
Apple apple1 = (Apple) apple.clone();
System.out.println("apple1 = " + apple1);
System.out.println("apple1 name = " + apple1.name);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}