• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method Overloading  RSS feed

 
Saumitra Tiwari
Ranch Hand
Posts: 39
Java PHP Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello guys,this question was asked in my last interview


I want to know why it is calling int not short?
Thanks.


 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the type of the numeric literal 2 in line 10 is int, so Java looks for the method that takes an int parameter.

If you want it to call the other method, you'll have to make sure the value is a short, for example by casting it:


How exactly Java determines which method to call is specified in paragraph 15.12 of the Java Language Specification. (This document is a bit difficult to read!).
 
manisha Mulchandani
Greenhorn
Posts: 20
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It calls method that accepts integer parameter because by default non-floating numbers are treated as integer unless you explicitly typecast them to another datatype like short,double etc.

so, to call method which accepts short use typecasting as follows:



Now call the method with the parameter i. So, it will call the method accepting short.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!