Pushparaj
Pushparaj

Reputation: 3

issue with Java.lang.Cloneable interface guidelines

As per java.lang.Cloneable interface:

The documentation for the Cloneable says -

Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.

But the following code is working correctly. It is not giving any error when I call ex1.clone.

package com.sriPushpa.thread;

public class exceptionHandling implements Cloneable {
    int a = 10;

    public static void main(String args[]) {
        exceptionHandling ex1 = new exceptionHandling();
        exceptionHandling ex2 = null;
        try {
            ex2 = (exceptionHandling) ex1.clone();

        } catch (CloneNotSupportedException e) {

            e.printStackTrace();
        }
        System.out.println("SUCCESS");
    }

}

Upvotes: 0

Views: 335

Answers (3)

Konrad Reiche
Konrad Reiche

Reputation: 29503

In your case the method of Object is invoked, since every class inherits from the java.lang.Object class. This clone() implementation does merely a field-by-field copy.

Cloneable is a marker interface. A marker interface is an interface that has neither methods nor variables defined but is used to provide type information about objects at run-time.

By adding this marker interface to your class definition it is guaranteed, that no CloneNotSupportedException will be ever thrown by invoking clone on your class.


A general advise is to take a look into Copy Constructor versus Cloning (Josh Bloch) whether you really want to use clone at all.

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 691765

The clone() method is implemented by java.lang.Object, as a protected method. Your code works because you're calling the clone() method from the same class as the one you clone.

If you want your object to be cloneable, you should override the clone() method and make it public:

public Object clone() throws CloneNotSupportedException {
    return super.clone();
}

Note that the doc doesn't say that implementing the Cloneable interface will always make clone() fail. It says that implementing it is not a guarantee that clone() will work. This is very different.

Upvotes: 1

Andy Thomas
Andy Thomas

Reputation: 86409

The root class java.lang.Object contains the method clone(). By default, if the concrete class implements Cloneable, the default class implementation makes a shallow copy.

From the method documentation:

The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. ... Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.

Upvotes: 3

Related Questions