0

I'm using a class (let's call it the BaseClass) from a package which implements the Cloneable interface, but it appears to do so by creating a new object and not by calling super.clone(). I have made a SubClass of this BaseClass, which then crashes when I attempt to clone it. In code, I have something like this:

// from library
class BaseClass implements Cloneable{
  public void clone(){
    BaseClass clone = new BaseClass(); // I guess?
    ...
    return clone;
  }
}

// my subclass
class SubClass extends BaseClass{
  public void clone() throws CloneNotSupportedException {
    return (SubClass) super.clone(); // throws ClassCastException
  }
}

One way would be to skip the extends BaseClass and just use a pointer, though it would really complicate my code.

What are my options if I really need to be able to make copies (one way or another)?

Thanks

  • 1
    The base class is wrong and violates the contract for `clone()`. Are you in a position to tell the maintainer to fix it? – Nayuki Dec 05 '16 at 15:48
  • I'm afraid it has been abandoned – user6502063 Dec 06 '16 at 15:49
  • Okay. Unfortunately you don't even have the option of bypassing straight to `Object.clone()`: http://stackoverflow.com/questions/3456177/calling-super-super-class-method – Nayuki Dec 06 '16 at 16:31

2 Answers2

0

Without seeing the exact BaseClass clone() method, I/we can't answer this for sure. But what I would tell you is that the default clone method located in Object will copy all fields over from the object that's being cloned to the new Object. Sometimes though you might want to override this functionality to clone referenced objects as well, rather than having both the original and the clone point to the same Object.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • Thanks. I made a new class with a pointer. Also made that pointer transient so I could implement Serializable. It works, at least :) – user6502063 Dec 06 '16 at 15:54
0

In your SubClass.clone, don't call super.clone() but create new SubClass your self:

  public void clone(){
    SubClass clone = new SubClass();
    //copy properties from this to clone
    return clone;
  }
ntahoang
  • 441
  • 5
  • 17
  • Yes, working around a wrong base class implementation by making your own wrong implementation. Uh huh. (But it would technically be right if SubClass is `final`.) – Nayuki Dec 05 '16 at 15:49
  • I think this is a fine approach given the situation, but the original object contains so much information that I'd rather not risk copying a field incorrectly or whatnot. Thanks though. For now, I chose to go for a class that just wraps the object – user6502063 Dec 06 '16 at 15:51