0

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;


}
SHOONYA
  • 352
  • 3
  • 14

1 Answers1

0

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.

Michael
  • 41,989
  • 11
  • 82
  • 128
  • But is there a way to initialize it in any other class than its deceleration class ? – SHOONYA Jan 16 '20 at 19:18
  • @SHOONYA No. You can modify the field value from another class, but in which case it cannot be `final`, and cannot be considered to be a constant. – Michael Jan 16 '20 at 19:20
  • Note, you can initialise it _using_ another class (by calling a method from another class, e.g. `private static final int x = SomeClass.computeX();`). – BeUndead Jan 16 '20 at 19:25