It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overloading Problem 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 "Overloading Problem " Watch "Overloading Problem " New topic

Overloading Problem

Deepak Bobal
Ranch Hand

Joined: Feb 06, 2008
Posts: 96

Constant dripping hollows out a stone....
Vladimir Kroupa

Joined: Dec 26, 2008
Posts: 28
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

Joined: Feb 06, 2008
Posts: 96
Thanks Vladimir.
I agree. Here's the link:
subject: Overloading Problem
It's not a secret anymore!