Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriden, inheritance and autoboxing

 
Julio Eneriz
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this two classes:

class B extends A {
String doStuff(Long l) {
return "B, Long";
}
}

public class A {

String doStuff(long l) {
return "A, long";
}

public static void main(String[] args) {
A a = new B();
B b = new B();

System.out.println(a.doStuff(0l));
System.out.println(a.doStuff(new Long(0l)));
System.out.println(b.doStuff(0l));
System.out.println(b.doStuff(new Long(0l)));
}
}

And I was expecting this output:
A, long
B, Long
A, long
B, Long

but I get

A, long
A, long
A, long
B, Long

I know it's not inheritance, but the behavior of the autoboxing seems a bit weird... Is it just "look the reference type and if you can autobox, do it, if not, go to the object type and try to see if something matches"

Weirder is that if I add this method to B:
String doStuff(long l) {
return "B, long";
}

The output is:
B, long
B, long (why not B, Long!)
B, long
B, Long

Is it something to memorize or there is a more general rule?

Thanks
 
Henry Wong
author
Marshal
Pie
Posts: 21204
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know it's not inheritance, but the behavior of the autoboxing seems a bit weird... Is it just "look the reference type and if you can autobox, do it, if not, go to the object type and try to see if something matches"


When it is time for the compiler to match the method call, it only knows by the reference type. As you mentioned, it is not inheritance. In the case of the B reference, it is overloading. And in the case of the A reference, the compiler only knows about the one method.

So... the first two calls goes to the same method (the second of the two actually have to be unboxed). And with the second two calls, since the compilers knows about the two overloaded options it will choose as expected.

Weirder is that if I add this method to B:


With the new method, the compiler generated the calls exactly as before -- except now inheritence is involved. You overriden the method in A.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic