Static and Final variable

xiaoxiao2021-03-05  25

First, Illegal Forward Refrence

I encountered a very eye-catching error when I wrote a class day before yesterday (after the problem is simplified):

PUNLIC FINAL CLASS Constants {

Public Static Int var2 = var1 1;

Public static int var1 = 1;

}

Compile time error (line 2):

Illegal Forward Refrence

I think carefully because VAR2 references are defined after Var2, it seems that the "declaration first" principle should be followed when defining static variables in Java.

Second, STATIC block

Still the last class, var1 and var2 are defined as final, and the value exists in a Properties file, and the value must be available before use:

System.getProperties (). Load (New FileInputStream ("constants.properties");

So the above code is placed in the Static block:

PUNLIC FINAL CLASS Constants {

STATIC {

System.getProperties (). Load (New FileInputStream ("constants.properties");

}

Public Static Final Int var2 = system.getproperties (). getproperty ("var2");

Public Static Final Int var1 = system.getproperties (). getproperty ("var1");

}

But when running VAR1 and VAR2 are not assigned, the Static block is not executed after DEBUG. So, "Final variables are calculated, assigning the compiler when compiling, so there is no need to perform the Static block at runtime.

转载请注明原文地址:https://www.9cbs.com/read-37211.html

New Post(0)