Unable to declare static variable inside of static method

后端 未结 6 2014
误落风尘
误落风尘 2020-12-14 03:03
class Foo {
    public Foo() { }
}

class Bar {
    static Foo foo = new Foo(); // This is legal...

    public static void main(String[] args) { 
        static int         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 03:49

    Declare the variable as final, not as static.

    Static means that there is one per class not one per instance of the class. Final means it can't be modified after creation. (Although note that making a reference final does not make the class it references immutable).

    In other words if you have a

    final String[] array = new String[3];
    

    You can no longer change that variable, for example if you wanted to assign to it a new array with a different size you could not. However you can modify the contents of the array.

    array[0] = "test";
    

    Because this modifies the contents, not the array itself.

    The same thing holds for any mutable objects.

提交回复
热议问题