General suggestion: use the copy constructor. In fact, only the class itself knows how to create a clone on its own. No class can clone an instance of another class. The idea is this:
public class Foo {
public List<Bar> bars = new ArrayList<Bar>();
private String secret;
public Foo(Foo that) {
this.bars = new ArrayList<Bar>();
for (Bar bar:that.bars) {
this.bars.add(new Bar(bar));
}
this.secret = new String(that.secret);
}
}
So, if we want to clone a foo, we just create a new one based on foo:
Foo clonedFoo = new Foo(foo);
This is the recommended way to clone an instance.
Copy constructor.
public ChildFoo extends Foo {
private int key;
public ChildFoo(ChildFoo that) {
super(that);
this.key = that.key;
}
}
foo , ChildFoo .
, . :
Foo a = new Foo();
ChildFoo b = new ChildFoo(a);
ChildFoo:
public ChildFoo(Foo that) {
super(that);
this.key = 0;
}
, b a, . , ( ) .