Why does all the clone() method return Object type?

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Why does all the clone() method return Object type?

Post 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?
I stay home. Don't call me out.
chunyi81
A great helper
Posts: 293
Joined: Sat Jun 21, 2003 4:19 am
Location: Singapore

Post 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.
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Post 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.
I stay home. Don't call me out.
Darko
Guru
Posts: 580
Joined: Fri Nov 11, 2005 9:34 am
Location: Calgary, Canada

Post 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.
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Post 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.
I stay home. Don't call me out.
Post Reply

Return to “Java”