javaclonecloneable

Dealing with final fields when overriding clone


I'm writing a class in which I have to override the clone() method with the infamous "super.clone() strategy" (it's not my choice).

My code looks like this:

@Override
public myInterface clone()
{
    myClass x;
    try
    {
        x = (myClass) super.clone();
        x.row = this.row;
        x.col = this.col;
        x.color = this.color; 
        //color is a final variable, here's the error
    }
    catch(Exception e)
    {
        //not doing anything but there has to be the catch block
        //because of Cloneable issues
    }
    return x;
}

Everything would be fine, except that I can't initialize color without using a constructor, being it a final variable... is there some way to both use super.clone() AND copying final variables?


Solution

  • Since the call to super.clone(); will already create a (shallow) copy of all the fields, final or not, your full method will become:

    @Override
    public MyInterface clone() throws CloneNotSupportedException {
        return (MyInterface)super.clone();
    }
    

    This requires that the superclass also implements clone() properly (to ensure that the super.clone() eventually reaches the Object class. All the fields will be copied properly (including final ones), and if you don't require deep clones or any other special functionality, you can use this and then promise that you'll never try to implement clone() again (one of the reasons being that it's not easy to implement it correctly, as evident from this question).