I am confused regarding overriding clone method in the class for which I want cloned object.
Object class has protected object method and as per the protected behavior which is When a method is protected, it can only be accessed by the class itself, subclasses of the class, or classes in the same package as the class.
As every class in Java extends from Object, so it should have clone method but still we are forced to override clone. Why is it required?
Also, I have read at some places to override the clone object and make it public. I wonder, why is it so?
All answers are welcome.
No you are not forced to override the
clonemethod. In inheritance, when you inherit a class, you are not forced to override it’s method. Its modifier being public or protected doesn’t make much of a difference. However, if you want to invoke a method directly onsuperclass reference, then that method has to bepublic. Protected methods are accessible only through inheritance. That is you can only access them throughsubclassreference. Or if you override the method, you can access them throughsuperkeyword.Having said that, you should not override
clonemethod, as it isbroken. Because, for a class to be cloned, you need to implement theCloneableinterface. And then your class uses theclonemethod ofObjectclass instead. Because,Cloneableinterface doesn’t exactly have any method forcloning. It would be a better option to useCopy Constructorinstead.For more details, I would suggest to go through this chapter of
Joshua Bloch'sEffective Java, which covers all aspects of usingclonemethod.Effective Java- Item # 11 – Override clone judiciously