Which overload will get selected for null in Java?

后端 未结 3 809
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 10:42

If I write this line in Java:

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

Which method will be called?

  • show
3条回答
  •  礼貌的吻别
    2020-11-22 11:14

    Neither. You'll get a compiler error asking you to clarify what method you want to call. You can do so by explicitly casting the first argument:

    showInputDialog((Object) null, "Write something");
    

    or

    showInputDialog((Component) null, "Write something");
    

    Update I should have known - never doubt Jon Skeet. The problem I've referred to above only occurs when it's impossible to determine which method is more specific. Here's a test case:

    public class Test {
    
      public void doSomething(String arg1, Object arg2) {
        System.out.println("String, Object");
      }
    
      public void doSomething(Object arg1, String arg2) {
        System.out.println("Object, String");
      }
    
      public static void main(String[] args) {
        Test test = new Test();
        test.doSomething(null, null);
      }
    }
    

    The above will give a compiler error.

提交回复
热议问题