• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Ambiguity in overloaded functions

 
Greenhorn
Posts: 4
Netbeans IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Netbeans IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That is convincing...thanks Knute.
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic