【问题标题】:Could not understand following lines in ITEM 11 of Effective Java无法理解有效 Java 的第 11 项中的以下行
【发布时间】:2012-02-06 01:52:06
【问题描述】:

我无法理解第 11 项下的以下行:从 Effective Java 明智地覆盖克隆

行为良好的克隆方法可以调用构造函数来创建正在构造的克隆内部的对象。 (第 55 页)

还提到'没有调用构造函数'。所以,我很困惑。

【问题讨论】:

    标签: java


    【解决方案1】:

    这意味着,给定类:

    class Foo implements Cloneable {
        private Bar bar;
        public Foo clone() {
            // implementations below
        }
    }
    
    class Bar implements Cloneable {
        public Bar clone() {
            return (Bar) super.clone();
        }
    }
    

    Foo 上的clone() 方法可以通过几种方式实现;不推荐第一个变体。

    不好

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

    【讨论】:

      【解决方案2】:

      您应该通过调用super.clone() 来获取返回的对象,而不是通过调用构造函数。这对于确保您正确解决类加载器问题很重要。但是如果通过调用super.clone() 获得的对象在返回之前需要进一步初始化——例如,如果你需要为引用成员创建一个新的包含对象,因为super.clone() 只会将引用复制到同一个对象——那么正常构造这些对象就完全OK了。

      【讨论】:

      • 所以,我们可以为成员对象调用构造函数。
      • Josh 的观点是,除了一小部分简单的案例外,这些细节都是复杂而令人困惑的。如果可以,请尝试使用其他东西。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 2020-01-28
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多