Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Boxing & Widening

 
Chris Judd
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone explain why this code outputs 3 4?

I don't understand why it would widen to Number and not to Long?

Thanks,
Chris

class Eggs {
int doX(Long x, Long y) { return 1; }
int doX(long... x) { return 2; }
int doX(Integer x, Integer y) { return 3; }
int doX(Number n, Number m) { return 4; }
public static void main(String[] args) {
new Eggs().go();
}
void go() {
short s = 7;
System.out.print(doX(s,s) + " ");
System.out.println(doX(7,7));
} }
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you mean 4 3.

When a short is sent to a method that expects an object reference, then that short can be boxed into a Short.

Long is not a superclass of Short.

Number is a superclass of Short.

So (short,short) will match (Number,Number).
 
Chris Judd
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's great. Thanks so much for clearing that up.

Cheers,
Chris
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic