When one thinks of cloning, we think of duplication that is more or less the exact same copy. Java cloning can be different depending on the type of clone.

To use the clone() method, interface Cloneable must be implemented. An exception called CloneNotSupportedException is thrown to indicate that the clone method in class Object has been called to clone an object, but that the object’s class does not implement the Cloneable interface. To use the clone() method, interface Cloneable must be implemented.
class Clyde_template implements Cloneable {
int age = 30;
String greeting = "Hi, I'm Clyde!";
public Object clone() throws CloneNotSupportedException {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
System.out.println (" Cloning not allowed. " );
return this;
}
}
}
/* Line 1 of our main class here throws the exception. */
public static void main (String[] args) throws CloneNotSupportedException {
This class implements the Cloneable interface, so we can get started. This class may be outside of our main class, but it is where all of our cloning magic happens. The class template holds an integer and a string. The public Object creates the clone constructor/object for use plus throws and catches necessary exceptions when cloning.
Meet Clyde. Clyde is your average 30 year-old man. Neither is Clyde or Clyde however because Clyde has been cloned once. Then we cloned Clyde’s first clone to make a new clone! This is the difference between a shallow and deep clone.
In Java, a shallow clone:
- Is jointed. Changing one changes the original object.
- Do not clone object references, only cloning primitive data types.
- Is made by default using Java’s clone() method.
public class Sprint4 {
public static void main (String[] args) throws CloneNotSupportedException {
Clyde_template Clyde2 = new Clyde_template(); // Creates Clyde2 from Clyde_template.
Clyde_template Clyde3 = (Clyde_template)Clyde2.clone(); // Creates deep clone Clyde3 from Clyde2.
Clyde2.age = 20;
Clyde2.greeting = "Hey, I'm Clyde.";
Clyde3.age = 5;
Clyde3.greeting = "Hey, I'm Cwyde!";
System.out.println("Age " + Clyde2.age + ". " + Clyde2.greeting);
System.out.println("Age " + Clyde3.age + ". " + Clyde3.greeting);
}
}
As you can see, using our above Clyde clone template we create a shallow clone named Clyde 2. Then we create a deep clone named Clyde 3. Cloning from any age, we change the age to obtain different versions of Clyde earlier in life. Not all Clyde(s) are the same after all!

Follow my original code on my GitHub profile! Sprint4.java is inside the Miscellaneous folder.







