• Post Reply Bookmark Topic Watch Topic
  • New Topic

Autocast  RSS feed

 
Breno Ribeiro
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In following code





book(shorRoom); method does not should work, returning the result of the method that recieve a Long because of autocast ?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
book(shortRoom) will call book(short).

I would expect book(intRoom) to cause a compile error. If you had a method that took (long a), then the int would be promoted to long and it would succeed. (Note that this is not called a cast, and there's no such thing as "autocast" in Java.) However, for the (Long a) signature, I would expect it to fail, because I don't think promotion + autoboxing are employed together.

If you want the details, they'll be in the JLS, but it's not an easy read.
 
Breno Ribeiro
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Understood.. I'll study more to understand better this question.

Thank you.
 
Campbell Ritchie
Marshal
Posts: 56586
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Jeff is correct; it won’t compile.
 
Breno Ribeiro
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I studied, and understood.

What happens is:
If a long (primitive), would be ok, because an int fits on long, and the upcasting would be made.
But if the int was an Integer, it won't be made, because when we're talking about wrapper classes, the test is done "IS-A", instead a FITs ON, so, an Integer isn't a Long.

In this case, the compiler promote the int to a Integer and compares to the Long, and concludes that an Integer ISN'T A Long.
And this is the answer.

Thank's all.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!