Gautam  Jha
Gautam Jha

Reputation: 130

why clone not working?

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code unreported exception java.lang.CloneNotSupportedException; must be caught or declared to be thrown at Test.main(Test.java:13) Java Result: 1

 public class  Color
 {
     public String ColorName()
     {
         return "Red";
     }
 }
 public class Test extends Color
 {
    public static void main(String args[])
    {
       Color MyShirt = new Color();
       Color MyBag = (Color) MyShirt.clone();

       System.out.println(MyShirt.ColorName());
       System.out.println(MyBag.ColorName());
    }
 }

Upvotes: 2

Views: 4347

Answers (4)

Bartek Maraszek
Bartek Maraszek

Reputation: 1414

The other answers are correct in pointing out that your class needs to implement Clonable and override the clone() method in order to work as expected:

class Color implements Cloneable{
    @Override 
    public Color clone(){
        Color c = new Color();
        c.name = this.name;
        return c;
    }
    // other methods
}

However, the most important thing about clone() is that you should always avoid using it.

Joshua Bloch explains in his book "Effective Java", that clone() is deeply broken and rightly recommends using a copy constructor instead. You can read more about it here.

Instead of using clone(), you should declare a copy constructor like this:

class Color{
    public Color(){ /* ... */ } // default constructor
    public Color(Color c){
        this.name = c.name; // copy all attributes
    }
    // other methods
}

and then use it to copy the object:

Color c = new Color();
Color other = new Color(c); // returns a copy of c

Upvotes: 3

user3735278
user3735278

Reputation: 269

Your class does not implement the Cloneable interface, hence is why this exception was thrown. This can be found right in Java API.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

Because you didn't implement Cloneable, and Object has a default implementation of clone() that only throws CloneNotSupportedException; I think you wanted something like this

public class Color implements Cloneable {
  protected String name = "Red";

  public String ColorName() {
    return name;
  }

  @Override
  public Object clone() {
    Color c = new Color();
    c.name = this.name;
    return c;
  }
}

Upvotes: 2

vitro
vitro

Reputation: 939

Your class must implement java.lang.Cloneable interface.

public class  Color implements Cloneable
{
    public String ColorName()
    {
        return "Red";
    }

    @Override
    public Color clone() {
        //return your cloned Color instance
    }
}

Upvotes: 1

Related Questions