Java 变量的可见性控制

Java 变量的可见性控制,java,Java,您已经在ArrayLesson1类中声明了数组,该数组对您的子类不可见,因此您得到了编译错误 你有两个选择 1在子类中创建构造函数以接受数组作为参数,并在子类中创建局部变量,然后将数组从ArrayLesson1传递给子类,如下所示: Exception in thread "main" java.lang.Error: Unresolved compilation problems: array cannot be resolved to a variable array cannot b

您已经在ArrayLesson1类中声明了数组,该数组对您的子类不可见,因此您得到了编译错误

你有两个选择

1在子类中创建构造函数以接受数组作为参数,并在子类中创建局部变量,然后将数组从ArrayLesson1传递给子类,如下所示:

Exception in thread "main" java.lang.Error: Unresolved
compilation problems:   array cannot be resolved to a variable  array
cannot be resolved to a variable

at Array.subclass.loopj(ArrayLesson1.java:40)   
at Array.ArrayLesson1.main(ArrayLesson1.java:25)
//in subclass
private int [] array;
public subclass(int [] array) {
   this.array = array;
}
public static void loopj(int [] array) {
   //Codes here
//
obj.loopj(array);
在ArrayLesson1类中这样调用:

Exception in thread "main" java.lang.Error: Unresolved
compilation problems:   array cannot be resolved to a variable  array
cannot be resolved to a variable

at Array.subclass.loopj(ArrayLesson1.java:40)   
at Array.ArrayLesson1.main(ArrayLesson1.java:25)
//in subclass
private int [] array;
public subclass(int [] array) {
   this.array = array;
}
public static void loopj(int [] array) {
   //Codes here
//
obj.loopj(array);
2修改loopj和loopk方法,以接受数组作为参数,如下所示:

subclass obj=new subclass(array); // Pass array like this
在你的数组中调用它,如下所示:

Exception in thread "main" java.lang.Error: Unresolved
compilation problems:   array cannot be resolved to a variable  array
cannot be resolved to a variable

at Array.subclass.loopj(ArrayLesson1.java:40)   
at Array.ArrayLesson1.main(ArrayLesson1.java:25)
//in subclass
private int [] array;
public subclass(int [] array) {
   this.array = array;
}
public static void loopj(int [] array) {
   //Codes here
//
obj.loopj(array);
3或者,如果要使用静态引用,则需要在使用它之前与classname.variablename一起使用,如下所示:

Exception in thread "main" java.lang.Error: Unresolved
compilation problems:   array cannot be resolved to a variable  array
cannot be resolved to a variable

at Array.subclass.loopj(ArrayLesson1.java:40)   
at Array.ArrayLesson1.main(ArrayLesson1.java:25)
//in subclass
private int [] array;
public subclass(int [] array) {
   this.array = array;
}
public static void loopj(int [] array) {
   //Codes here
//
obj.loopj(array);

如果有帮助,请告诉我。

您的问题是什么?