Java继承和Scope变量

Ric*_*rd3 1 java inheritance scope

该计划是:

class A
{
   int i = 10;
}
class B extends A
{
   int j = 20;
}
class C extends B
{
   int k = 30;
}
class D extends C
{
   int m = 40;
}

public class asg2
{
   public static void main(String[] args)
   {
       A[] a = {new A(),new B(), new C(), new D()};

    System.out.println(a[3].i); //No error!!!
    System.out.println(a[2].j); //throws error 
    System.out.println(a[1].k); //throws error (Understood why error)
    System.out.println(a[0].m); //throws error (Understood why error)
}
Run Code Online (Sandbox Code Playgroud)

}

我理解为什么最后两次抛出错误.但我不明白为什么第二个print语句会抛出错误.第一个顺利运行.

asg2.java:29: error: cannot find symbol         
System.out.println(a[2].j);                                    
                       ^
symbol:   variable j                    
location: class A                                              
Run Code Online (Sandbox Code Playgroud)

man*_*uti 5

编译器看不到a[2]类型的元素C.它看到它的类型,A因为这是声明的数组的类型.因此,它不能接受访问属于子类的字段A.如果将元素强制转换为C,则compile将接受它:

System.out.println(((C) a[2]).j); // compiles OK
Run Code Online (Sandbox Code Playgroud)