File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Cloning - a doubt regarding super.clone() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Cloning - a doubt regarding super.clone()" Watch "Cloning - a doubt regarding super.clone()" New topic
Author

Cloning - a doubt regarding super.clone()

Ritesh Srivastava
Greenhorn

Joined: Jul 06, 2005
Posts: 26
class Employee implements Cloneable
{
public Employee clone() throws CloneNotSupportedException
{
return (Employee) super.clone(); // Line 1
}
. . .
}

Here Employee class is extending Object class so when we call super.clone in Line 1 then it should give object of Object class . How come this line does not throws a ClassCastException? How is "downcasting" allowed although super.clone() here will return an object of type Object?
I need to understand Line 1 only.
[ March 22, 2007: Message edited by: Ritesh Srivastava ]
Gad Flailimbs
Greenhorn

Joined: Mar 21, 2007
Posts: 15
To sum it up, you aren't having a problem because employee's parent class is the Object class You are ending up getting an Employee object in your return with the values equivalent to the clone of any attributes of the Object class.

It won't throw a ClassCastException because the clone method will return an Employee and the definition of an Employee envelops any parent classes (Like Object or if you were sneaky you might make a Person class, Object -> Person -> Employee).

I hope this makes sense.


Java Game:<br /><a href="http://pokemon.ele-mentalfury.com/" target="_blank" rel="nofollow">http://pokemon.ele-mentalfury.com/</a><br />Webcomic:<br /><a href="http://ele-mentalfury.com/" target="_blank" rel="nofollow">http://ele-mentalfury.com/</a>
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
[ replying to the original poster, not the interleaved reply ]

No, looks like you need to re-read the basic stuff about object-oriented programming.

If a method is declared to return Object, that means it will return Object, or any subclass of Object. In some cases, the programmer knows that the type actually returned by a method call, in a particular situation, is going to be a particular subclass of the declared return type. In that situation, the programmer may entirely legitimately cast to the subclass.

The clone() method of Object is declared to return Object, but will actually return the same type as the object on which it is called.
[ March 22, 2007: Message edited by: Peter Chase ]

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Ritesh Srivastava
Greenhorn

Joined: Jul 06, 2005
Posts: 26
Got it. Thanks guys
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Cloning - a doubt regarding super.clone()