Menu

#2 No clone for super class.

open
nobody
None
5
2004-06-01
2004-06-01
No

The generated clone method doesn't handle fields in
super classes. Currently the clone method looks like
this for a class without any cloned fields:
public Object clone() {
Abc inst = new Abc();
return inst;
}

I propose that it should look like this instead:
public Object clone() {
Abc inst = null;
try {
inst = (Abc) super.clone();
} catch (CloneNotSupportedException e) {
// If this happens, then we shouldn't have
// overridden clone in the first place.
throw new RuntimeException(e);
}
return inst;
}

The big difference being that the instance returned by
super.clone() will have been initialised with all the
fields that should be passed on to a clone from the
super class.

Discussion

  • Stephan Schloepke

    Logged In: YES
    user_id=34859

    This seems to be important however the JavaDoc for
    Object.clone() tells exactly how it should be done.

    public/protected clone() throws CloneNotSupportedException
    {
    MyClass tempClone = (MyClass)super.clone();
    // Do what is needed to clone
    tempClone.xxxx = xxxx.clone()
    return tempClone;
    }

    Only this actually ensures that the contract for clone is
    fullfilled. The reason is quite simple. Clone needs to return an
    object of the EXACT same type. If for instance you have a
    Class B derived from A and only A implements the clone
    than B.clone().getClass() != B.Class which is incorrect. In
    case that B only has primitive values (say a boolean added)
    an extra overwriting of clone is not necessary. Also if any
    object part or whatever in a clone is not cloneable than the
    whole object isnt cloneable so there is no need to try and
    continue whenever a CloneNotSupportedException is raised.
    Therefor we should continue to throw it to the caller.

    Hope that helps :-)
    Stephan

     
  • Bjorn Martensson

    Logged In: YES
    user_id=993097

    Yes, the spec. dictates that super.clone() is called. I
    don't understand why this isn't fixed. Seems like an easy
    fix to make to me.

    If CloneNotSupportedException should be thrown or not is a
    matter of taste. In some classes, it can never be thrown,
    and then to force all callers to write code around it seems
    like wasted effort to me.

     
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.