• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why this outout

 
Sireesha Mullapudi
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Why the following code is not giving compile time error


Thanks
scjp1.4
 
Joe Harry
Ranch Hand
Posts: 10112
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lakshmi,

Why do you think that it should give a compile time error?? The method method(null) matches the string version and prints string as o/p. If you remove the static method that takes String as argument, it prints object as the O/P. It's a good question. Can anyone please explain this behaviour.

Regards,
Jothi Shankar Kumar. S
 
anvesh charuvaka
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

The null Literal can be cast into any type of Object Reference.
So any one of the given method()'s can be called but the compiler tries to choose the most specific one.

Now the null matches the call for method(Object )
then it also matches the call for method(String )

since the string version is more specific the call is made to the method(String ) version.

But if you overload the method with Integer
metod(Integer ) then the complier does not know which one to call because
The String version is as specific as Integer version so the compiler shouts that the call is "AMBIGUOUS"
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3715
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can almost hear someone say, "how do you know X is more specific than Y?"

Simple answer is, if X extends Y directly or indirectly, X is more specfic than Y. If there is no direct or indirect inheritance relationship between X and Y, both are equally specific.

So Integer is more specific than Number and Number is more specific than Object. But String and Integer(or Number) are equally specific.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,


this ambiguity can be seen for interfaces as well:





This code produces:
class A


but if you delete the method // for A's
it is ambigous and the line foo(a); in main cannot compile.
Same would be true for foo(null);




Yours,
Bu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic