首页 > 解决方案 > 调用父类和子类中可用的方法时,在多态中选择了哪种方法?

问题描述

我不明白为什么该ab.m3()方法调用父类的函数而不是子类的函数。我想也许将 new 传递Integer给方法可能会调用父类的方法,因为Integeris anObject所以我尝试使用 anint但它仍然给了我相同的结果!

public class A {

    public void m1(){
        System.out.println("A.m1");
    }
    public void m2(){
        System.out.println("A.m2");
    }
    public void m3(Object x){
        System.out.println("A.m3");
    }
}

public class B extends A{

    public void m1(){
        System.out.println("B.m1");
    }
    public void m2(int x){
        System.out.println("B.m2");
    }
    public void m3(int x){
        System.out.println("B.m3");
    }

    public static void main(String[] argv){
        A aa = new A();
        A ab = new B();

        int num = 2;

        ab.m1();
        ab.m2();
        ab.m3(new Integer(2));
        ab.m3(num);

    }
}

输出:

B.m1
A.m2
A.m3
A.m3

标签: javapolymorphism

解决方案


B.m3不会覆盖A.m3,因为参数列表不兼容。

A因为is中唯一匹配的方法A.m3,并且因为 中没有覆盖B,所以A.m3它将被调用。


推荐阅读