问题描述:

Is it possible to declare array as instance variable?

public class Dog

{

public static void main(String[] args)

{

Some code like creating objects

}

}

class Dogtesr

{

int[] nums;

nums = new int[5]; // This shows an error

}

网友答案:

Statements (nums = new int[5];) (as opposed to variable / method / class declarations) needs to be in functions, e.g. the constructor:

class Dogtesr
{
   int[] nums;
   public Dogtesr()
   {
      nums = new int[5];
   }
}

Or you can simply initialize nums as part of the declaration:

int[] nums = new int[5];
相关阅读:
Top