java, overloading functions?

Started by
7 comments, last by johnnyBravo 20 years ago
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,
Advertisement
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

<hr align="left" width="25%" />
Jack Hoxley <small>[</small><small> Forum FAQ | Revised FAQ | MVP Profile | Developer Journal ]</small>

oh yeah actually i dont think ive even tried the code i posted on c++. only the way u said
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?
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.
yea, what i think the java libs had were like

String function()
{
return ...
}

int function(int num)
{
return ...
}
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.
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?
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

This topic is closed to new replies.

Advertisement