Page 1 of 1
Why does all the clone() method return Object type?
Posted: Sat May 27, 2006 8:15 am
by ImLazy
As I know, every clone() method provided by JDK returns Object. Why don't they return explicit type? I have to convert the type every time I use their clone().
What's the benefit of returning Object?
Posted: Sat May 27, 2006 9:07 am
by chunyi81
From what I remember about Java, every Java class implicitly extends the Object class, which is the base class of all Java classes. The Object class has a clone method which is inherited by any Java class, unless you specifically implement the clone method in the Java class you are writing to override the clone method in the Object class.
Posted: Sat May 27, 2006 9:29 am
by ImLazy
Every clone() method provided by JDK are overriden methods except the one in Object class, because the clone() method in Object is protected. If one class want to provide clone() method, it must override it. And my question is why don't the provide clone() methods which return explicit types.
Posted: Sat May 27, 2006 9:51 am
by Darko
I never really understood the need for clone(), so I never used it, but I looked it up, best to read it for yourself:
http://mindprod.com/jgloss/clone.html
Btw, Roedy's glossary is an excellent resource for Java. I haven't checked it in a while, but he is probably keeping it up-to-date.
Posted: Sun May 28, 2006 3:31 pm
by ImLazy
I think I've found the reason. It's very simple: in java 1.4 or earliear versions, overridden methods can not change the return type. So all the clone() methods, which are overridden from Object, must be Object type.