简体   繁体   中英

how to initialize static final variable from other class in java

I want to initialize Final.value in Main method. Is it possible to initialize static final constant in other class than in its deceleration class?

public class Main {

    public static void main(String[] args) {
        //I want to initialize Final.value in Main method.
    }

}

class Final {
    //here is the static final variable which can be assigned vai a static block
    //but how do I initialize it in the main method if I don't use the static block?
    static final int value;


}

You cannot. Your perception might be that main happens before everything else, so it is safe to initialise things there, but that is incorrect.

Consider the following code.

class Scratch
{
    static
    {
        System.out.println(Foo.i);    
    }

    public static void main(String[] args)
    {
        Foo.i = 100;
    }
}

class Foo
{
    static int i;
}

It does not print 100. It prints 0 because there are other things which happen before main .

Making the field final does not change that fact.


You have two options for static initialization. In a static initializer block, like you showed, or in-line:

static final int value = 421

Java prevents you from doing what you want to do for a good reason: because it is likely to lead to bugs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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