为什么在Java继承期间,在父母班级中声明的阵列在子类中不可见


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错误

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

但是,即使班级和,为什么这种方法会导致错误 宣布数组的方法是公开的?

即使该方法被声明为公共,并不意味着您可以访问其中声明的对象...

int [] array 属于静态方法主,而不是类,范围为comp。不同,除非您修改范围,否则您将永远无法读取/编写该对象。

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

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

int[] array在方法内声明。这使其成为局部变量。局部变量的可见度有限,仅对声明的方法可见。即使从同一类的方法也无法访问它。

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

最新更新