加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 00:52:14 所属栏目:Java 来源:网络整理
导读:参见英文答案 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”);} publ
参见英文答案 > 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读