• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cloning - a doubt regarding super.clone()

 
Ritesh Srivastava
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[ 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 ]
 
Ritesh Srivastava
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it. Thanks guys
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic