GorkemSahin GorkemSahin - 3 years ago 79
Java Question

If the return type 'Object' works with all the value types to return, why do we bother declaring specific return values for functions?

I'm currently an intern trying to learn from more experienced developers and one of them declares all functions to return Objects. I asked him why and he replied "It works with everything".

Well then, why should I declare functions with specific return value types?

Answer Source

The whole idea is how you want to interface the returned object, all classes in java extends Object so yes you can do this, but when specifying the return type to be Object, Object will be the actual interface, so you will need a cast to be able to use any additional methods or attributes defined in your specific class.

In addition to the headache of casting you cannot safely assume that the return object is really an instance of your presumed class, so you will need to check also if the return object is an instance of the class you want to be interfaced by.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download