Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CloneNotSupportedException even when implementing Cloneable

Tags:

java

java-7

Why does the following code throw CloneNotSupportedException in JDK7 but NOT in JDK6?

public class DemoThread extends Thread implements Cloneable {

    /**
     * @param args
     */
    public static void main(String[] args) {
        DemoThread t = new DemoThread();
        t.cloned();
    }

    public DemoThread cloned()
    {
        try {
            return (DemoThread) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

}
like image 781
Manish Avatar asked Dec 27 '12 09:12

Manish


People also ask

How do I handle CloneNotSupportedException?

How to Handle CloneNotSupportedException. To avoid the CloneNotSupportedException , the Cloneable interface should be implemented by the class whose objects need to be cloned. This indicates to the Object. clone() method that it is legal to create a clone of that class and helps avoid the CloneNotSupportedException .

Why do we need to implement a cloneable interface?

Cloneable interface is implemented by a class to make Object. clone() method valid thereby making field-for-field copy. This interface allows the implementing class to have its objects to be cloned instead of using a new operator.

Can we use clone method without cloneable interface?

The clone() method of Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException. The clone() method is defined in the Object class.

How are cloneable interface CloneNotSupportedException and clone () method are related?

A class must implement the Cloneable interface if we want to create the clone of the class object. The clone() method of the Object class is used to create the clone of the object. However, if the class doesn't support the cloneable interface, then the clone() method generates the CloneNotSupportedException.


1 Answers

Here's Thread's implementation of clone() in SE 7

/**
 * Throws CloneNotSupportedException as a Thread can not be meaningfully
 * cloned. Construct a new Thread instead.
 *
 * @throws  CloneNotSupportedException
 *          always
 */
@Override
protected Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
}

Threads were never designed to be cloned. Doing some reading sparked off one of the comments I found this summed it up quite well : "But we either have to disallow cloning or give it meaningful semantics - and the latter isn't going to happen." -- David Holmes

like image 110
bowmore Avatar answered Oct 05 '22 23:10

bowmore