Java – when the difference between methods is a parameter subtype, null is passed to the overriding method

See English answer > which overload will get selected for null in Java? 3

Why does the virtual machine call this method f (null) {system. Out. Println ("B");}?

Why not 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);
    }
}

Solution

Call the method with the most specific parameter type This is the rule

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>