首页 > 解决方案 > 超类方法和子类方法

问题描述

请帮助我了解此代码,谢谢!

class Parent {
    int num = 4;

    protected void foo() {
        System.out.println("foo() of Parent");
    }

    static protected void bar() {
        System.out.println("bar() of Parent");
    }
}

class Child extends Parent {
    int num = 5;

    protected void foo() {
        System.out.println("foo() of Child");
    }

    static protected void bar() {
        System.out.println("bar() of Child");
    }
}

public class Test {
    public static void main(String[] args) {
        Parent f1 = new Parent();
        System.out.println(f1.num);

        Parent f2 = new Child();
        System.out.println(f2.num);

        Child c = new Child();
        System.out.println(c.num);

        f1.foo();
        f2.foo();
        c.foo();

        f1.bar();
        f2.bar();
        c.bar();
    }
}

输出如下:

4
4
5
foo() of Parent
foo() of Child
foo() of Child
bar() of Parent
bar() of Parent
bar() of Child

你能告诉我 Person f2=new Child() 是否是多态性吗?如果是这样,为什么'f2.num'的输出是 4,而 'f2.foo()' 是 'foo() of Child'。我认为这与超类的静态bar()有关。请告诉我原理,非常感谢。

标签: javaoop

解决方案


是的,Person f2=new Child()是一个Runtime Polymorphism。你对f2.num'is 4的输出是绝对正确的,但是f2.foo()is foo() of Child。由于静态成员被继承到子类,但有一些限制:

  • 您可以覆盖它们
  • bar()如果您在子类中重新定义了一个方法,那么父类的继承方法 ( ) 将被隐藏

因此,当您使用正常过程运行时多态性f2的引用创建对象时(将子对象与父对象绑定)但是当您重新定义该方法时,父方法被隐藏并且子类方法被映射到该语句Parent classbar()bar()f2.bar()


推荐阅读