• Post Reply Bookmark Topic Watch Topic
  • New Topic

Working with methods  RSS feed

 
Urs Waefler
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following class:
What will it print when compiled and run? It will not compile, if //1, //2, and //3 are commented out. I really do not understand this answer. I would kindly ask for a clarification.
 
s ravi chandran
Ranch Hand
Posts: 579
6
Java jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I remember reading an article which explained that in case of multiple methods having compatible data types, the one which accommodates the value closest (least bit size) would be selected.

By default, if you run the program, the output is
Here you get Integer because you already have a method with param type Integer.

Second result has more to do with the native value. As casting to an object with not be optimal, it selected the one with native data type.

If you comment out 1, 2, and 3, you get error as Integer/ int are not compatible with Long. They would not be justified also, even if it were allowed. The bit size would not be utilized properly for a value of lower bit size.

If you cast it, it might work or else keep the native long option available.

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there is an exact match, that one gets used. So if there was a method that took an int, b would use it. After that, it looks for types that can be widened. That's why long is picked. It doesn't look at autoboxing or varargs until after that "tie break".

Why you ask? Back in Java 4, autoboxing and varargs didn't exist. When java 5 was introduced, they didn't want the method called to change in the same scenario! So autoboxing and varargs "tie break" later in the order.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!