Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which overload will get selected for null in Java?

If I write this line in Java:

JOptionPane.showInputDialog(null, "Write something"); 

Which method will be called?

  • showInputDialog(Component parent, Object message)
  • showInputDialog(Object message, Object initialSelectionValue)

I can test it. But in other cases similar to this, I want to know what happens.

like image 963
Martijn Courteaux Avatar asked Oct 09 '09 18:10

Martijn Courteaux


People also ask

What happens if we pass null in a method in Java?

When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn't happen unless we intentionally pass null value.

How do you pass null?

You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter. However, you can also use a void type for parameters, and then check for null, if not check and cast into ordinary or required type.


1 Answers

The most specific method will be called - in this case

showInputDialog(Component parent, Object message) 

This generally comes under the "Determine Method Signature" step of overload resolution in the spec (15.12.2), and in particular "Choosing the Most Specific Method".

Without getting into the details (which you can read just as well in the spec as here), the introduction gives a good summary:

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.

like image 98
Jon Skeet Avatar answered Oct 11 '22 20:10

Jon Skeet