Lucian Enache
Lucian Enache

Reputation: 2520

Java : casting in clone() method

Last week in our java course we were introduced the Object class and some of its methods one of these methods was clone() and when our teacher explained us this method we were told that every-time that we clone an an object we have to down-cast the returned object by clone() because clone() returns an object of the Object type.

Therefore, I couldn't find a reason why would this method prefer to return a generic Object when it could easily get the type of the cloned object with another method like getClass() and handle the down-casting automatically.

oh btw this is no homework it's just my personal curiosity that led me to ask this (my teacher could give me an precise answer so I decided to let him be for now :D )

Upvotes: 0

Views: 1977

Answers (2)

fluffy
fluffy

Reputation: 5314

It's because the java.lang.Object base class signature for clone() returns Object. You can override the returned type on a subclassed method, but it's not really necessary anyway. Since you already know the class that you're cloning, you can simply cast it to the class that you are cloning and things will be fine.

Rereading your question, I notice you ask why it doesn't just get the type of the cloned object and handle the down-casting automatically. Internally it sort of is doing this already; it's really more that clone() is returning a specific object that's been upcast to Object, which all Java objects inherit from. However, the compiler isn't about to change the type of the variable you're assigning clone()'s return value to.

Since you already know the class you're trying to get at, there isn't any reason you can't just cast it yourself.

Upvotes: 5

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

Java is a result of many revisions and slightly strange design choices. For some reason the designers of Java decided that clone always returns something of type Object, while as you point out yourself the getClass method always returns something of type Class<? extends A> if the method is called on a class A.

The co-variant return types of Java allow you to override clone to have the correct return type, but standard practice is to just live with this short-coming and cast the object after calling clone.

Upvotes: 1

Related Questions