Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not understand following lines in ITEM 11 of Effective Java

Tags:

java

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.

like image 205
darkapple Avatar asked Oct 09 '22 19:10

darkapple


1 Answers

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.

Bad

public Foo clone() {
    Foo result = new Foo(); // This is what "no constructor is called" refers to.
    result.bar = new Bar();
    return result;
}

Good

public Foo clone() {
    Foo result = super.clone();
    result.bar = new Bar(); // this is the constructor you're allowed to call
    return result;
}

Also good

public Foo clone() {
    Foo result = super.clone();
    result.bar = result.bar.clone(); // if the types of your fields are cloneable
    return result;
}
like image 183
millimoose Avatar answered Oct 12 '22 11:10

millimoose