|
![]() |
名片设计 CorelDRAW Illustrator AuotoCAD Painter 其他软件 Photoshop Fireworks Flash |
|
一、illegal forward refrence 前天写一个类时碰到一个很眼生的编译错误(问题简化后): punlic final class Constants{ public static int VAR2 = VAR1 + 1; public static int VAR1 = 1; } 编译时出错(第2行): illegal forward refrence 仔细一想,是因为VAR2引用的VAR1在VAR2之后定义,看来在Java中定义static变量时应遵循“声明先于使用”的原则。 二、static块 还是上一个类,VAR1和VAR2定义成final,值存在一个properties文件中,在使用前必须将值load进来: System.getProperties().load(new FileInputStream("constants.properties")); 于是将上面的代码放在static块中: 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"); } 但在运行时VAR1和VAR2没有被赋值,debug后发现static块根本没有执行。于是顿悟:final变量在编译时便被编译器计算、赋值,因此在运行时没有必要执行static块。 返回类别: 教程 上一教程: Java数据库编程中查询结果的表格式输出 下一教程: Java 理论与实践: 关于非常的争论 您可以阅读与"static与final变量"相关的教程: · Java变量的缺省(默认)值--只有类的instance变量和static变量才有 · Thinking:Java中static、this、super、final用法 · Java中static、this、super、final用法 · Java Threading中的final变量 · Java中static、this、super、final用法 |
![]() ![]() |
快精灵印艺坊 版权所有 |
首页![]() ![]() ![]() ![]() ![]() ![]() ![]() |