【问题标题】:Passing null to the overridden method when the difference between methods is the parameter subtype [duplicate]当方法之间的区别是参数子类型时,将null传递给被覆盖的方法[重复]
【发布时间】:2013-10-03 13:55:04
【问题描述】:

输出:B

为什么虚拟机调用这个方法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);
    }
}

【问题讨论】:

  • 请检查您的格式...不清楚
  • 看来我们需要再次挖掘规范...

标签: java oop jvm


【解决方案1】:

调用最具体的参数类型的方法。这就是规则 这是来自JLS section 15.12.2.5

如果多个成员方法既可访问又适用于方法调用,则有必要选择一个为运行时方法分派提供描述符。 Java 编程语言使用选择最具体方法的规则。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-24
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    相关资源
    最近更新 更多