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 😀 )
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 toObject, which all Java objects inherit from. However, the compiler isn’t about to change the type of the variable you’re assigningclone()‘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.