(Java)如何调用覆盖"继承"来自超级班的方法?

时间:2018-05-24 09:54:02

标签: java class methods override inherited

让我们直接进入代码:

Father.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");
    }

}

Son.java:

public class Son extends Father {

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

}

Main.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类型。无论如何我能得到想要的答案吗?

提前致谢

P.S。:实际上,我想从Father类中调用方法Print(Son类)。有可能吗?

2 个答案:

答案 0 :(得分:5)

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

也就是说,在DoSmth(Father object)个实例中都会执行Father,因此即使public void Print(Father object)类已经Father,它也会调用Son类的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

你会得到输出

A = {"type": "dict", "schema": {"name": {"type": "string"}}}
B = {"type": "dict", "schema": {"age": {"type": "integer"}}}
C = {"type": "dict", "schema": {"gender": {"type": "string"}}}

schema = {'field':{'type':'list','anyof_schema':[A,B,C]}}

v = Validator(schema)

challenge = {'field':[{'name':'a name'}]}

v.validate(challenge)
True

答案 1 :(得分:0)

这是因为您在父实例上调用Print方法。如果您不是将对象作为参数传递并调用object.Print(),那么您应该得到预期的结果