开发者

Using arrays in a class

开发者 https://www.devze.com 2023-02-28 11:45 出处:网络
Why can I do: public class ThisTest { int[] anArray= new int[10]; public int[] getArr(){ 开发者_JAVA技巧anArray[0] = 100;

Why can I do:

public class ThisTest {
    int[] anArray  = new int[10];             
    public int[] getArr(){
   开发者_JAVA技巧     anArray[0] = 100;
        anArray[1] = 200;
        return anArray;                    
    } 
}

But not:

public class ThisTest {
    int[] anArray  = new int[10];     
    anArray[0] = 100;
    anArray[1] = 200;   
}


because you cannot assign values outside a method or a initialization block.

So this is also legal:

public class ThisTest {
    int[] anArray  = new int[10];     
    {     // This is the initialization block
        anArray[0] = 100;
        anArray[1] = 200;   
    }
}


You haven't declared a method. You can't just write code in the sky:)


You probably want this:

public class ThisTest {
    int[] anArray  = new int[10];  

    public ThisTest()
    {   
        anArray[0] = 100;
        anArray[1] = 200;   
    }
}

The constructor is the appropriate place for the initialization you're doing. You can also use the initialization block as MByD shows, which is functionally equivalent to putting the statements at the beginning of your constructor (convenient if you are overloading the constructor and this initialization is common to all).

0

精彩评论

暂无评论...
验证码 换一张
取 消