• Post Reply Bookmark Topic Watch Topic
  • New Topic

Overloading  RSS feed

 
Honey Rathore
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello all,

we know overloaded constructors and methods must have different argument list
than what if we have a constructor of argument short and another constructor of argument int
and we call them by creating an instance with parameter value 2.
which constructor should be called now?
because both can take '2' as a value.





 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When used as a literal, 2 is always an int. You can test this by removing the constructor that takes a long - you will get a compiler error, because even though 2 fits in a short it just isn't one.

To use 2 in a call to a constructor or method that takes a short you have two options:
1) explicitly cast it:
2) use a variable of type short before you call it: The final keyword I used is optional but by using it I'm making sure the compiler actually removes variable s and replaces it with value 2 instead. Consider this test:
When I decompile this, I get my first code again:
 
Honey Rathore
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but if i have a constructor of argument int and another constructor of argument long
and i pass 2 as a value than it will be received by the constructor with int as an argument
and if i pass 2147483650 as a value(which is too large for int),it won't compile (obviously)
but when i comment the int-constructor(with int as an argument)
and than pass value 2
it is received by the long-constructor(prints 2long).

well, i have some idea what's going on here
but can anyone clear the whole operation.
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The most specific constructor or method is always chosen (do a search for what that means, it has been discussed before). In short, if you pass an int, then the compiler will use the constructor with an int if available. Otherwise it will take a look at constructors that have a wider type like long, or a boxed type like Integer. If it has both there are special rules that determines which goes first, widening (int to long) or boxing (int to Integer).
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my experiment int 2 is first promoted to long, and then
boxed as an Integer. Boxing to Long is not done, however.
Jim...
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java™ Language Specification section. It is really easy to read. That last statement is a lie.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!