In method overloading, is it possible to have different return types for a overloaded method? for example,
void foo(int x) ;
int foo(int x,int y);
double foo(String str);
in general object oriented programming, is it possible?
In method overloading, is it possible to have different return types for a overloaded method? for example,
void foo(int x) ;
int foo(int x,int y);
double foo(String str);
in general object oriented programming, is it possible?
For most programming languages that support method overloading (Java, C#, C++, ...), if the parameter types are different, then the return types can also be different.
As long as you don't do something like this:
int foo (int i, int has_default=0);
double foo (long l);
/* Skipping to the function call. */
foo (1);
you should be okay. The above code will cause problems because it could be trying to call either function. It can get really bad if you're using C++, and you return pointers instead of primitives or references...
Check out this awesome answer, http://stackoverflow.com/questions/442026/function-overloading-by-return-type
In short, most statically typed languages don't, but some dynamically typed languages can.
Edit: The "In short" answer applies to overloading strictly by return type. As others have pointed out, if the parameter lists differ, and can be resolved by the compiler, then each method may return a different type. It is possible to overload methods only by return type in ADA, since the return value cannot be ignored, and the compiler can resolve the method call using this information.
In a class, there can be several methods sharing the same name but differ in
By depending on the parameters provided for the method, in the run time, compiler determines which version of the method to execute.
An overloaded method may or may not have different return types. But return type alone is not sufficient for the compiler to determine which method is to be executed at run time.