New Post New Thoughts ;-)
Hey rewind all I said in my previous post. I think there is a bug in javap that made me think that. (or I have just drunk two much steaming old good Java
coffee ;-) )
First of all, it is not weird that a call for a method on an object of type StringBuffer ends up in a call for method in a non hierarquical related class as String is ?
I thought the complier looked for the method to invoke in the type and supertypes of the variable that helds the reference. Later the dynamic binding magic can ocurr.
Besides, if an object of a type could receive methods from another non-hieraquical-related type we would have encountered a flaw in the type checking with which Java reassure us.
In
http://usuarios.tripod.es/JoseBotella there is available a free nice though bare-bone class file parser. I fed the parser with the class file spawned from the following program:
the result can be checked by anyone:
--------------------------------------------------------
10 atag(6)CONSTANT_Methodref
0 0 class_indexjava/lang/StringBuffer
3 3
0 0name_and_type_index toString()Ljava/lang/String;
22 16
-------------------------------------------------------- what the hell is this?
This is the constant pool entry number 6. It contains a symbolic reference for a method called toString that takes no argument and it returns a String. But this method is defined in the class StringBuffer.
Now the output for the previous program produced by javap:
Method Test()
0 aload_0
1 invokespecial #1 Method java.lang.Object()
4 getstatic #2 Field java.io.PrintStream out
7 new #3 Class java.lang.StringBuffer
10 dup
11 ldc #4 String "a"
13 invokespecial #5 Method java.lang.StringBuffer(java.lang.String)
16 invokevirtual #6 Method java.lang.String toString()
19 invokevirtual #7 Method void println(java.lang.String)
22 return In line #16 javap reports that the constant pool entry 6 is the toString method from the String class. This is in contradiction with all the previous stuff.
I have checked it also with the following program:
And the same discrepancy happens.
So it seems to me that javap has a bug here.
I think we should postpone our discussion untill we have checked this.