java – 当方法之间的差异是参数子类型时,将null传递给重写方法

前端之家收集整理的这篇文章主要介绍了java – 当方法之间的差异是参数子类型时,将null传递给重写方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Which overload will get selected for null in Java?3个
> 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

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.

原文链接:https://www.f2er.com/java/129927.html

猜你在找的Java相关文章