Java

本类阅读TOP10

·使用MyEclipse开发Struts框架的Hello World!(录像1)
·hibernate配置笔记
·AOP编程入门--Java篇
·linux下Tomcat 5.0.20 与 Apache 2 安装/集成/配置
·在win2003下整合了整合Tomcat5.5+ apache_2.0.53+ mod_jk_2.0.47.dll
·构建Linux下IDE环境--Eclipse篇
·Jsp 连接 mySQL、Oracle 数据库备忘(Windows平台)
·ASP、JSP、PHP 三种技术比较
·Tomcat5.5.9的安装配置
·AWT GUI 设计笔记(二)

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
static与final变量

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

一、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块。




相关文章

相关软件