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
User avatar
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 » Sat May 27, 2006 8:15 am

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 » Sat May 27, 2006 9:07 am

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.

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

Post by ImLazy » Sat May 27, 2006 9:29 am

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 » Sat May 27, 2006 9:51 am

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.

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

Post by ImLazy » Sun May 28, 2006 3:31 pm

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”