简体   繁体   中英

Could not understand following lines in ITEM 11 of Effective 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.

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;
}

You should obtain the returned object by calling super.clone() , rather than by calling a constructor. This is important to make sure you get classloader issues right. But if the object you get by calling super.clone() needs further initialization before returning -- for example, if you need to create a new contained object for a reference member, since super.clone() would just copy the reference to the same object -- then it's perfectly OK to construct those objects normally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM