Unable to declare static variable inside of static method

后端 未结 6 2007
误落风尘
误落风尘 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:41

    I suppose that your expectation was behaviour like a static local variable with an initializer in a C function, which is initialized only once, namely in the first call of the function, but not in subsequent calls.

    Java static fields is similar to C static local variables in that static fields are initialized only once, namely when the class is loaded.

    Regarding the other answers mentioning it, final has nothing to do with this! final means that the value of a variable/field cannot be changed after it has been initialized.

    The idiomatic solution in Java is not using static fields in the first place, except for constants and things like caches and registries.

    Often, a better solution is to write a new class instead that holds the value you would wanted to keep in the "static" variable as a regular (non-static) field. You can initialize it in the field declaration or in the new class's constructor, and then do the computation you wanted to do in a (non-static) method.

提交回复
热议问题