为什么在父类中声明的数组在java继承期间在子类中不可见?

时间:2017-02-23 10:56:41

标签: java arrays inheritance

class Parent
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int[] array=new int[]{1,2,3,4,5};
    }
}
class Child extends Parent
{
    int x=array[2];
    public void MyPrint()
    {
        System.out.println(x);
    }
}

我得到的错误是,

  

Main.java:18:错误:找不到符号int x = array [2];         ^符号:变量数组位置:类子1错误

是的,我们可以将数组作为参数传递给方法,代码将编译。但是,即使已声明数组的类和方法是公共的,这种方法为什么会导致错误?

3 个答案:

答案 0 :(得分:0)

因为数组未在父类中声明,而是在main方法中声明。您必须声明成员变量:

class Parent
{
    protected int[] array=new int[]{1,2,3,4,5}; // will be visible for the Child
}

答案 1 :(得分:0)

  

但是为什么这种方法会导致错误,即使是类和   声明数组的方法是公共的吗?

即使该方法被声明为public也不意味着您可以访问在其中声明的对象...

int [] array 属于静态方法main而不属于类,范围是compl。不同,除非你修改范围,否则你永远无法读/写那个对象..

答案 2 :(得分:0)

int[] array在方法中声明。这使它成为local variable。局部变量的可见性有限,只有声明它的方法才能看到它。即使从同一类的方法也无法访问它。

class Parent
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int[] array=new int[]{1,2,3,4,5}; // local variable, 
        // visible only inside main method
    }
}

如果要从子类访问超类中声明的变量 - 将变量声明为 实例变量。

class Parent {

   int[] array=new int[]{1,2,3,4,5}; // instance variable, 
   // is visible for other methods in same class
   // and for subclasses. 

}