• Post Reply Bookmark Topic Watch Topic
  • New Topic

Ambiguity in overloaded functions  RSS feed

 
Greenhorn
Posts: 4
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an overloaded function 'f' as follows:

1. public void f(int i, long j){System.out.println("1");}
2. public void f(int...i){System.out.println("2");}
3. public void f(long l, long p){System.out.println("3");}
4. public void f(int j, int k){System.out.println("4");}

With the function call: f(1,2), the output is: 4.

My questions are the following:
a. Why is the compiler choosing #4 to execute and not the rest?
b. If I remove 4 and replace it with: 5. public void f(long j, int k){System.out.println("5");}, why does the compiler now give an error complaining of ambiguous function defintions when 'f' is called?
 
Sheriff
Posts: 4289
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a) Java wants to behave as consistently as possible. That means it wants to keep old behaviors first before new behaviors. Var args is relatively new, so Java picks the exact f(int, int).

b) With f(int, int) gone, it is now not clear whether you want f(int...) or one of the other int/long methods. There is no "precedence" so it returns an ambiguous method call error.
 
Samreen Tahir
Greenhorn
Posts: 4
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is convincing...thanks Knute.
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Samreen Tahir wrote:That is convincing...

However, the simplest way to avoid stuff like this is not to overload methods - or, if you do, make it impossible for there to be any ambiguity.

Overloading is something you should use very sparingly. It can't be avoided with constructors, but if you find yourself coding lots of them, consider a Builder instead.

HIH

Winston
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!