• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inability to resolve widening/boxing

 
kaku kohli
Greenhorn
Posts: 6
Firefox Browser Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ilja Preuss and Corey McGlone thanks for the accurate explanation you have given...
i totally understood it.
please help me with this similar problem i got stuck with..



i am expecting it to produce following output:

BMW getmodelno long... i

because widening is preferred by the compiler over autoboxing/unboxing

but i am getting compiler error:
reference to getModelno method is ambiguous..

please tell me how can it be...?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
Please don’t post new messages on old threads; I have split this discussion from this old thread.
Please review the Java Language Specification section about choosing overloaded methods. This example shows how confusing and hazardous overloading can be, and how careful you have to be about it. You think you are choosing between boxing an argument 5 to an Integer versus widening it to a long, but that is not actually what you have written.
The parameters for those methods are of type long[] and Integer[]. You can widen an int to a long, but not to a long[]. You can box it to an Integer, but not to an Integer[].
If you try boxing, you can possibly match one method, and if you try widening, you can match the other.
So you can only match those methods with boxing AND, or widening AND. So they are not more specific than each other. So I tried it and got this compiler error:
BMW.java:16: error: reference to getModelno is ambiguous, both method getModelno(long...) in BMW and method getModelno(Integer...) in BMW match
b.getModelno(5);
^
 
kaku kohli
Greenhorn
Posts: 6
Firefox Browser Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell Ritchie..
I understood that Java Language Specification section.
Specially this line in Java Language Specification section:
A method m1 is strictly more specific than another method m2 if and only if m1 is more specific than m2 and m2 is not more specific than m1.

In my code, each method is not more specific than the other one. I have to make a method more specific to make my code work.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done

Remember what I said yesterday:
This example shows how confusing and hazardous overloading can be, and how careful you have to be about it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic