Effective Java: Analysis of the clone() method

前端 未结 5 662
南笙
南笙 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:11

    A class doesn't have to provide its own implementation of clone in order to be cloneable. It can delegate that to its cloneable superclass. Here comes the catch: clone must always return an instance of the same class as the instance it is called on. That is impossible to achieve in the described case if an explicit constructor is called. If the class overridng clone is final, on the other hand, this would be fine.

提交回复
热议问题