java static 静态变量初始化
static final int NUMBER_OF_MONTHS = 12;
static final float PI = (float) 22 / 7;
如果你想使一个静态变量在其它地方可以引用的话,如下
public static final int NUMBER_OF_MONTHS = 12;
public static final float PI = (float) 22 / 7;
写在函数中
public class MainClass {
public static void main(String[] arg) {
final int FEET_PER_YARD = 3; // Constant values
final double MM_PER_INCH = 25.4; // that cannot be changedSystem.out.println(FEET_PER_YARD);
System.out.println(MM_PER_INCH);
}}
静态变量如何初始化
Java类中可以定义一个static块,用于静态变量的初始化。如:
public class Test {
public static int _i;
static {
_i = 10;
}
}
public class Test { public static int _i; static { _i = 10; } }
当然最常用的初始化静态变量的操作是在声明变量时直接进行赋值操作。如:
public class Test {
public static int _i = 10;
}
public class Test { public static int _i = 10; }