Which overload will get selected for null in Java?

后端 未结 3 812
没有蜡笔的小新
没有蜡笔的小新 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:15

    In your particular case the more specific method will be called. In general, though, there are some cases where the method signature can be ambiguous. Consider the following:

    public class Main {
    
        public static void main(String[] args) {
            Main m = new Main();
            m.testNullArgument(null);
        }
    
        private void testNullArgument( Object o )
        {
            System.out.println("An Object was passed...");
        }
    
        private void testNullArgument( Integer i )
        {
            System.out.println("An Integer was passed...");
        }
    
        private void testNullArgument( String s )
        {
            System.out.println("A String was passed...");
        }
    }
    

    In this case, the compiler can't decide between the method that takes an Integer and the method that takes a String. When I try to compile that, I get

    reference to testNullArgument is ambiguous, both method testNullArgument(java.lang.Integer) in testnullargument.Main and method testNullArgument(java.lang.String) in testnullargument.Main match
    

提交回复
热议问题