L
lallous
Hello,
I tried to use the clone() by letting my class implement clonable, however,
I don't want to guard my code whenever I duplicate my class.
The clone() must always succeed (why would it fail other than when there is
no memory to create a new instance)?
In worst cases one would create a new instance and do member copying to the
new instance:
class Class1 implements Clonable
{
public static class innerclass
{
// has duplicate method too
}
public Object clone()
{
private int x1;
try
{
return super.clone();
}
Catch (CloneNotSupportedException e)
{
Class1 newobj = new Class1();
newobj.x1 = x1;
return newobj;
}
}
public Class1 duplicate()
{
Class1 newentry = new Class1();
newentry.x1 = x1;
return newentry;
}
}
Now in Class2:
method()
{
Class1 c2, c1 = new Class1();
c2 = c1.clone(); // <-- cannot w/o casting from Object to Class1.
c2 = (Class1) c1.clone(); // works.
c2 = c1.duplicate(); // <-- works fine
}
Can someone tell me is the 'duplicate()' is safe, why should I use clone()
and not my own cloning code (same as C++ copy constructors)?
Does Object.clone() clones my private variables too in MyClass?
Is it safe to duplicate static inner classes using duplicate?
I tried to use the clone() by letting my class implement clonable, however,
I don't want to guard my code whenever I duplicate my class.
The clone() must always succeed (why would it fail other than when there is
no memory to create a new instance)?
In worst cases one would create a new instance and do member copying to the
new instance:
class Class1 implements Clonable
{
public static class innerclass
{
// has duplicate method too
}
public Object clone()
{
private int x1;
try
{
return super.clone();
}
Catch (CloneNotSupportedException e)
{
Class1 newobj = new Class1();
newobj.x1 = x1;
return newobj;
}
}
public Class1 duplicate()
{
Class1 newentry = new Class1();
newentry.x1 = x1;
return newentry;
}
}
Now in Class2:
method()
{
Class1 c2, c1 = new Class1();
c2 = c1.clone(); // <-- cannot w/o casting from Object to Class1.
c2 = (Class1) c1.clone(); // works.
c2 = c1.duplicate(); // <-- works fine
}
Can someone tell me is the 'duplicate()' is safe, why should I use clone()
and not my own cloning code (same as C++ copy constructors)?
Does Object.clone() clones my private variables too in MyClass?
Is it safe to duplicate static inner classes using duplicate?