Effective Java: Analysis of the clone() method

前端 未结 5 664
南笙
南笙 2020-12-09 04:48

Consider the following from Effective Java Item 11 (Override clone judiciously) where Josh Bloch is explaining what is wrong with the clone() contract .

5条回答
  •  忘掉有多难
    2020-12-09 05:04

    It's because typical implementations of clone() look like this:

    public class MyClass implements Cloneable {
      protected Object clone() {
        MyClass cloned = (MyClass) super.clone();
        // set additional clone properties here
      }
    }
    

    In this way you can inherit the cloning behavior from your superclass. It's widely assumed that the result of a clone() operation will return the correct instance type based on the object it was called on. Ie. this.getClass()

    So if a class is final, you don't have to worry about a subclass calling super.clone() and not getting the right object type back.

    public class A implements Cloneable {
        public Object clone() {
           return new A();
        }
    }
    
    
    public class B extends A {
        public Object clone() {
           B b = (B)super.clone(); // <== will throw ClassCastException
        }
    }
    

    But, if A is final, no one can extend it, and thus it's safe to use a constructor.

提交回复
热议问题