A very Kentson compilation error was encountered when writing a class the 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 2nd):
Illegal forward refrence
Think carefully, because the VAR1 of the VAR2 reference is defined after VAR2, it seems that the static variable should be defined in Java with the principle of "declaration prior to use".
Two, static block
Or the previous class, VAR1 and VAR2 are defined as final, values exist in a properties file, and the value load must be entered before use:
System.getproperties (). Load (new FileInputStream ("Constants.properties"));
The above code is then 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");
}
However, at run time VAR1 and VAR2 were not assigned, and debug found that the static block was not executed at all. So epiphany: The final variable is computed and assigned at compile time, so it is not necessary to execute a static block at run time.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.