繁体   English   中英

在主类或主方法中声明数组有什么区别?

[英]What's the difference between declaring array in main class or in main method?

我一直在尝试用Java声明数组,就像教程中说的那样,但是收到一个错误。 这是我的代码:

public class ArrayExample {

   private static final int SIZE = 15;

   /*   this works   */
   int[] arrayOfInt = new int[SIZE];

   /*  but this doesn't work, says "cannot find symbol"  */
   int[] arrOfInt;
   arrOfInt = new int[SIZE];


   public static void main(String[] args) {

      /*  but here it works; why? what's the difference? */
      int[] arrOfInt;
      arrOfInt = new int[SIZE];
   }
}

我在教程中找不到这种差异的解释。 为什么第二个声明不起作用,而main方法中的第三个声明起作用?

您不能将赋值语句作为类定义的一部分来编写。

可以使用第一种方法(首选),也可以将赋值移动到构造函数中(在这种情况下不是必需的,但是如果在构造对象之前不知道大小,则可能很有用-然后可以将其作为参数传递给构造函数)。

int[] arrOfInt;

public ArrayExample()
{
    arrOfInt = new int[SIZE];
}

您甚至可以通过以下方式将变量的初始化插入到匿名代码类中,而无需使用构造函数:

int[] arrOfInt;

 {
arrOfInt = new int[SIZE];
} 

当你这样做

int[] arrayOfInt = new int[SIZE];

编译器将读取arrayOfInt并将记住使用new int[SIZE]对其进行初始化。

此时将不会进行arrayOfInt初始化。

执行此操作时:

int[] arrOfInt;
arrOfInt = new int[SIZE];

编译器读取arrOfInt但是当它到达第二行时,它没有找到arrOfInt的类型,请记住,此时编译器可能没有读取所有变量,因此它说它找不到arrOfInt ,总之它不会检查它是否已读取arrOfInt 。名为not的变量,因为尚未完成其完整处理,并且不在初始化块中。 您仍然在代码的声明块中。

方法是一个声明+初始化块,因此编译器允许您在两个不同的点声明和初始化变量。

对于初始化,您可以使用构造函数或实例初始化块或静态初始化块。

  • 加载类时,静态初始化块将执行一次。
  • 实例初始化块在每次创建类实例时执行,并且在类的构造函数中对super的调用完成后,将按照类中的定义执行它们。

您不能将非固定值声明为静态方法,所以这是错误的

int []arrOfInt;
public static void main(String[] args) {
      arrOfInt = new int[SIZE];
}

你可以这样解决

int []arrOfInt=new int[SIZE];
    public static void main(String[] args) {
    }
}

或像这样

class ArrayExample{
   int []arrOfInt;
   public static void main(String args[]){
        ArrayExample a = new ArrayExample();
        a.arrOfInt=new int[a.SIZE];
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM