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

Java 是否可以通过父类引用访问子类变量?,java,inheritance,parent-child,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 Chec

有人能告诉我这个代码的输出吗

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?
    }
}

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


在B中,您可以通过执行method或super.method来选择调用哪个方法,以指定是否调用super实现。

Yes。有一个特殊的工具可以为您提供任何Java程序的输出。它叫Java。你自己试试吧!有人能告诉我这个代码的输出吗?你是否需要一只手臂来亲自尝试和执行它?此外,我认为它是不完整的。如果你没有IDE可用,请使用这个:。@keppil-我没有IDE,也不知道ideone。感谢你没有像其他学者那样愤怒地指责我:
    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