aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriden, inheritance and autoboxing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriden, inheritance and autoboxing" Watch "Overriden, inheritance and autoboxing" New topic
Author

Overriden, inheritance and autoboxing

Julio Eneriz
Greenhorn

Joined: Nov 28, 2007
Posts: 15
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
Sheriff

Joined: Sep 28, 2004
Posts: 19070
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overriden, inheritance and autoboxing