• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

boxing method call doubt

 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


What will be the output for the above program?
1)Object called
2)Number called-answer
3)Compiler Error
4)Runtim Exception


Why the answer is Number? I thought it is ambiguous between Object & Number. So the answer is compiler error.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, it's not ambiguous.

The call matches both methods, but the one with parameter Number is more specific than the one with parameter Object. The most specific method that matches will be chosen in this case.
 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I just forgot.
 
Yogvinder Singh Ghotra
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone explain this to me in detail??
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here the int literal 10 is first boxed to Integer which is then widened to Number.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15482
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When two methods match the call, Java chooses the most specific method. See section 15.12.2.5 of the Java Language Specification. In this case, the method that takes a Number is more specific than the method that takes an Object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic