参见英文答案 >
Which overload will get selected for null in Java?3个
> Strange Java null behavior in Method Overloading 4个
OUTPUT:乙
> Strange Java null behavior in Method Overloading 4个
OUTPUT:乙
为什么虚拟机调用此方法f(null){System.out.println(“B”);}?
为什么不f(null){System.out.println(“A”);}
public class Test{ public static class A {} public static class B extends A {} public void f(A a) {System.out.println("A");} public void f(B a) {System.out.println("B");} public static void main(String[] args) { new Test().f(null); } }
解决方法
调用具有最特定参数类型的方法.这是规则
这是从 JLS section 15.12.2.5
这是从 JLS section 15.12.2.5
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.