Archived

This topic is now archived and is closed to further replies.

johnnyBravo

java, overloading functions?

Recommended Posts

hi i want to overload functions like in java like in c++ eg
String getValue()
{
   return ...;
}

int getValue()
{
    return ...;
}
when i try this in the java it says error and wont let me do it. But in the java libs they seem to have done it. thanks,

Share this post


Link to post
Share on other sites
From looking at your code, you''re only changing the return type - I dont think thats allowed (dont think C/C++ allows it either). Probably too ambiguous which return type is wanted, hence the compiler doesn''t like it

Try just overloading based on the parameter list.

Jack

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Actually, you can''t do that in C++ either. Says MSDN: "An overriding function in a derived class cannot differ from a virtual function in a base class only by its return type". Of course, if you omit the virtual keyword, the derived class will hide the base class'' method, not override it. That''s bad.
quote:
Original post by johnnyBravo
But in the java libs they seem to have done it.

Really? Where?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
That would be often unambigous, I suppose that''s why they disallowed that. Consider you have another pair of functions:

void foo(String x) {}
void foo(int x) {}

Then call it like this:

foo(bar.getValue());

Now which function would that call? You don''t know if getValue() returns an int or a string. And how could you tell it to the compiler, i.e. how to make the above statement unambiguous? A cast won''t do, so it would probably require new syntax. Not worth it.

Share this post


Link to post
Share on other sites
quote:
Original post by johnnyBravo
yea, what i think the java libs had were like

String function()
{
return ...
}

int function(int num)
{
return ...
}


Yes, that''s possible because the arguments are different. In your first example, the methods differed ONLY by return type.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Anonymous Poster
That would be often unambigous, I suppose that''s why they disallowed that. Consider you have another pair of functions:

void foo(String x) {}
void foo(int x) {}

Then call it like this:

foo(bar.getValue());

Now which function would that call? You don''t know if getValue() returns an int or a string. And how could you tell it to the compiler, i.e. how to make the above statement unambiguous? A cast won''t do, so it would probably require new syntax. Not worth it.


um, wouldnt bar.getValue() have a known return type?

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
um, wouldnt bar.getValue() have a known return type?

No. read it again.


"Sneftel is correct, if rather vulgar." --Flarelocke

Share this post


Link to post
Share on other sites