If two overloaded methods are-test(Object xyz) and test(Customer cust)[Assume Customer is a class with member name of type String].Now if we call test(null), which method will be called? why?

Showing Answers 1 - 4 of 4 Answers

Guest

  • Nov 13th, 2005
 

The method - test(Customer cust) will be called. This will happen because while resolving calls to overloaded methods, the Java compiler incorporates a 'Most Specific' algorithm. Since the value null is assignable to both an 'Object' reference and a 'Customer' reference, the compiler chooses the Customer reference as an execution of the general rule that argument Types which are more specialized ('Customer' in this case) to handle a parameter passed to a method will receive that parameter as opposed to a more general type ('Object' in this case) . Consider an analogous example to make it easy to understand what I mean :Class OverloadingTest{ private void overloadedMethod(Object objectReference) { System.out.println("You passed an Object"); } private void overloadedMethod(String stringReference) { System.out.println("You passed a String"); } public static void main(String args[]) { new Test().overloadedMethod("This is a String parameter"); }}This should make it easy for you to understand what will happen and why. Our parameter - "This is a String parameter", is a String and is assignable to both an Object reference AND a String reference BUT the compiler rightly chooses the method with the String argument (i.e the second method) since it's String argument is a MORE SPECIFIC match to our String parameter than the Object argument of the first method (In the case of a null parameter it might seem meaningless but the general rule that I mentioned above, i.e a more general match is discarded in the presence of a relatively more specfic match, is followed). It certainly makes sense - what do you say ? So the second method is called and the message - "You passed a String" is printed to the console.CHEERS !!!

bhanu prasad

  • Nov 19th, 2005
 

every thing is Object in the world

  Was this answer useful?  Yes

Abhishek

  • Jan 13th, 2006
 

Thanks. I appreciate your time to explain in detail.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions