2

我们直接上代码:

父亲.java:

public class Father {

    public void DoSmth(Father object) {
        // Do something else and print
        Print(object);
    }

    public void Print(Father object) {
        System.out.println("Father");
    }

}

儿子.java:

public class Son extends Father {

    public void Print(Son object) {
        System.out.println("Son");
    }

}

主.java:

public class Main {

    public static void main(String[] args) {

        Father o1 = new Father();
        Son o2 = new Son();

        o1.DoSmth(o1);
        o1.DoSmth(o2);

    }

}

所以,我想得到:

Father
Son

但是,我得到:

Father
Father

我真的不太明白为什么(对于 o1.DoSmth(o2))它从父类调用方法,因为 o2 是 Son 类型。反正我能得到想要的答案吗?

提前致谢

PS:实际上,我想从父类内部调用(子类的)方法打印。可能吗?

4

2 回答 2

5

public void Print(Son object)不覆盖public void Print(Father object). 它超载它。

也就是说,DoSmth(Father object)在这两种情况下都在实例上执行,因此即使类确实覆盖了它Father,它也会调用public void Print(Father object)类。FatherSon

如果将Son类方法更改为:

@Override
public void Print(Father object) {
    System.out.println("Son");
}

并将您的更改main为:

public static void main(String[] args) {
    Father o1 = new Father();
    Son o2 = new Son();

    o1.DoSmth(o1);
    o2.DoSmth(o2);
}

你会得到输出

Father
Son
于 2018-05-24T09:55:47.883 回答
0

This is because you are calling the Print method on the Father-instance. If you instead of passing the object as the parameter and called object.Print() you should get your expected result

于 2018-05-24T09:58:45.903 回答