Why is the clone() method kept in Object?
I开发者_如何转开发f a class is not Cloneable
no object of this class can be cloned. Then why is clone()
kept in the Object
class and not in Cloneable
interface?
It was a design error in Java (yes, Java is not perfect!).
It's better to avoid cloning in Java. For example Josh Bloch points out in Effective Java, Item 11:
The Cloneable interface was intended as a mixin interface (Item 18) for objects to advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its primary flaw is that it lacks a clone method, and Object's clone method is protected. You cannot, without resorting to reflection (Item 53), invoke the clone method on an object merely because it implements Cloneable. Even a reflective invocation may fail, as there is no guarantee that the object has an accessible clone method. Despite this flaw and others, the facility is in wide use so it pays to understand it.
If you want your objects to be cloneable, implement a copy constructor or copy method.
Cloneable is a marker interface, acts like an attribute to the user/developer to see if the class is clonebale.
clone() is kept in Object class because in your clone() implementation it is advised that you call super's clone(), this can happen only if the super class has a clone function even if its not marked cloneable(by implementing Cloneable) hence keeping the clone() function in Object makes sense.
clone() creates a different instance of the class altogether which like constructor should call super's method to create a full fledged instance.
精彩评论