【问题标题】:Java inheritance and Scope of variableJava继承和变量范围
【发布时间】:2015-09-08 11:29:10
【问题描述】:

节目是:

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

}

我明白为什么最后两个抛出错误。 但我不明白为什么第二个打印语句会引发错误。 第一个运行顺利。

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

【问题讨论】:

    标签: java inheritance scope


    【解决方案1】:

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

    System.out.println(((C) a[2]).j); // compiles OK
    

    【讨论】:

      【解决方案2】:

      数组a 中的每个条目都是A 类型。它实际上可能包含BCD 的实例,但该变量的类型为A,因为这是声明数组的方式。所以你不能访问 A 没有的字段(除非你转换成另一种类型,明确告诉编译器你认为该对象是什么类型)。

      【讨论】:

        猜你喜欢
        • 2014-07-26
        • 1970-01-01
        • 2017-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        相关资源
        最近更新 更多