Cloneable in Java

Cloneable interface is one of the mistake in design in Java. At least I think so 🙂

A class should be implementing Cloneable interface if that class wants to be cloned along with overriding clone() method from Object class. This combination of compulsion makes it quite unusual to implement.

Code below:

public class Student implements Cloneable {
    private int studentId; 
    private String studentName; 
    // getter/setters of attributes and some constructors

    @Override public Student clone() throws CloneNotSupportedException { 
        return (Student) super.clone(); 

//Demo class
public class CloneableDemo {
  public static void main(String[] args) throws CloneNotSupportedException { 
     Student student1 = new Student(101, "Jacob"); 
     System.out.println(student1.getStudentId() + " - " + student1.getStudentName()); 
     Student student2 = student1.clone(); 
     System.out.println(student2.getStudentId() + " - " + student2.getStudentName()); 

As you can see Student Class is implementing Cloneable interface and also overriding clone() method from Object class making it public (default is protected).

Now lets consider following two scenarios:

  1. Class not implementing Cloneable interface,
  2. Class not overriding clone() method or marking the clone() method public.

First, When a class does not implement Cloneable interface but overrides clone() method and still try to be cloned we get like below exceptions. i.e.

Exception in thread “mainjava.lang.CloneNotSupportedException: com.tektutorial.models.Student

Second, When a class implements Cloneable interface but does not override clone() method or override but does not make it public then we get compile time error. i.e.

The method clone() from the type Student is not visible

So you must have observed the heat of compulsion of implementing Cloneable interface AND overriding clone() method both.

Above code can be found in GIT and you can play with it

The above can be found in GIT.

Hope this clears your doubt about Cloneable interface.