是否可以通过父类引用访问子类变量?

时间:2014-01-24 12:21:01

标签: java inheritance parent-child

有人可以告诉我这段代码的输出吗?

public Class A {

    public int count = 5;    

    public void test() {
        // some code
    }    
}

public Class B extends A {

    public int count = 10;

    public void test() {
        //some code
    }
}

public Class Check {

    A a = new A();
    A b = new B();

    public void myTestMethod() {
        a.count; //should call A?
        a.test; //should call A?
        b.count; //which count is called here? compiler error?
        b.test; //should call B?
    }
}

2 个答案:

答案 0 :(得分:3)

    a.count;    => yes you can
    a.test;     => yes you can
    b.count;    => count = 5; its didn't shows the compiler error its return the 5.
    b.test;  => Yes

答案 1 :(得分:1)

Java继承允许扩展测试覆盖或隐藏它扩展的类中的方法。因此,如果B扩展A并且两者具有相同的方法,那么当您调用b.method()时,它将在B中调用该方法。

在B内部,您可以选择调用哪个方法method()super.method()来指定是否调用超级实现。