• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Overloading Problem

 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Greenhorn
Posts: 28
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The null reference can always be cast to any reference type (according to JLS3).
That makes it legal to pass the null refrerence as an argument to the method x.

The other question is - of the two overloaded methods, why is method B chosen?
When more than one applicable method is available, Java chooses the most specific method.

Quoting JLS3:

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.



So in your example, invocation of method x(B b) could also be handled by method x(A a) (B is a subtype of A, so it can be upcast to A) .
On the other hand, invocation of method x(A a) cannot be handled by method x(B b) (you cannot pass instance of A to a method that expects it subtype, B. Imagine passing an instance of Object to a method that takes a String - not legal).
That makes method x(B b) the more specific of the two.
 
Deepak Bobal
Ranch Hand
Posts: 96
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Vladimir.
 
reply
    Bookmark Topic Watch Topic
  • New Topic