I read that the object class are the root of all classes.So in this case the object class has a .clone method . Objects such as arraylist etc have the clone method but what about our custom classes are they extended from the object class as well ?? If so why dont the instances of those classes have the .clone method ? We have to impliment the cloneable inteface to get that. Any suggestions?
You'll also notice that the clone() method in Object is protected. It does exist in all your custom classes, but it's still protected. The default behaviour is to do a shallow copy, but only (as John said) if the class implements Cloneable.
The clone method is designed a bit strangely (and I suspect the language designers would do it differently if they were starting from scratch again), but if you're using it then the approach is:
- Implement Cloneable
- Override clone(), making it public (making it more accessible is fine, it's only less accessible that the compiler will complain about)
- Just call super.clone() if you're happy with the default behaviour, or add whatever you need if you're not.
protected methods are also visible within the same package - so your comparison method isn't the equivalent. Outside the package they're only accessible to subclasses via inheritance - you can call it from a subclass on the same instance, but not on another instance.
It is also worth looking at what Joshua Bloch says about clone(), in Effective Java (old edition), or you can buy the new edition. There are other ways to copy objects, eg with copy constructors or factory methods.
Joined: Oct 16, 2011
Oh that got cleared up ... I am sorry I didnt realize that protected memebers are available to derived class instances only if they are in the same package.!!!
Thanks for clearing that up..
Joined: Oct 13, 2005
Rajesh Khan wrote:. . . protected memebers are available to derived class instances only if they are in the same package.!!! . . .