I could not understand following line under item 11 : Override clone judiciously from Effective Java
A well-behaved clone method can call constructors to create objects internal to the clone under construction. (pg:55)
It was also mentioned that 'no constructor are called'. So, I'm confused.
What that means is that, given the classes:
class Foo implements Cloneable {
private Bar bar;
public Foo clone() {
// implementations below
}
}
class Bar implements Cloneable {
public Bar clone() {
return (Bar) super.clone();
}
}
the clone()
method on Foo can be implemented in a few ways; the first variant is not recommended.
public Foo clone() {
Foo result = new Foo(); // This is what "no constructor is called" refers to.
result.bar = new Bar();
return result;
}
public Foo clone() {
Foo result = super.clone();
result.bar = new Bar(); // this is the constructor you're allowed to call
return result;
}
public Foo clone() {
Foo result = super.clone();
result.bar = result.bar.clone(); // if the types of your fields are cloneable
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With