1、创建FinalTest类,里面有一个final常量x
class FinalTest{ public static final int x = 3; static { System.out.println("FinalTest static block"); } } public class MyTest8 { public static void main(String[] args) { System.out.println(FinalTest.x); } }
然后在Main方法里打印fianl常量。打印结果
3
2、然后去掉final,
class FinalTest{ public static int x = 3; static { System.out.println("FinalTest static block"); } } public class MyTest8 { public static void main(String[] args) { System.out.println(FinalTest.x); } }
打印结果为:
FinalTest static block 3
3、将fianl常量改为随机生成
class FinalTest{ public static int x = new Random().nextInt(3); static { System.out.println("FinalTest static block"); } } public class MyTest8 { public static void main(String[] args) { System.out.println(FinalTest.x); } }
打印结果
FinalTest static block 1
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!