Java clone() method

前端 未结 3 1273
慢半拍i
慢半拍i 2021-01-13 18:45

I read Effective Java by J.Bloch and here was wrote:

If you design a class for inheritance, be aware that if you choose not to provide a well-behave

3条回答
  •  旧时难觅i
    2021-01-13 19:23

    Of course you can implement B.clone().

    The problem which J. Bloch refers to is (IIRC), that without a good A.clone() method, the private fields within A can not be cloned properly in B. Simple example:

    public class A {
      private String myText;
      public A (String myText) {
        this.myText = myText;
      }
      public String getExtendedText() {
        return "Hello something " + myText;
      }
    }
    
    public class B extends A implements Cloneable {
        private int someValue;
        // getter/setter
    
        public clone() {
            // how can you now provide a good clone with A.myText being cloned?
        }    
    }
    

提交回复
热议问题