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?
super.clone();
already? – Udellamyclass
might be derived fromsomeClass
, which (apart from allsomeClass
members), also hasrow
,col
andcolor
. Sosuper.clone()
won't copy such members. – Roblessuper.clone()
– Roblesclone()
works (which isn't surprising). That's why I didn't want speculation. Facts work better than guesses on SO. – Udellarow
,col
andcolor
, just as @Robles said. – Cordwainsuper.clone()
will copy all the fields (otherwise what would be the advantage of calling it?), so the copying by hand is unnecessary. You can replace the whole method withreturn (MyInterface)super.clone();
. – UdellamyClass
, and not in the class it's derived from (which I guess being Object)? – Cordwain