static与final变量

一、illegal forward refrence

前天写一个类时遇到一个很眼生的编译错误(问题简化后):

1 ExpandedBlockStart.gif ContractedBlock.gif punlic final  class  Constants dot.gif {
2InBlock.gif  public static int VAR2 = VAR1 + 1;
3InBlock.gif  public static int VAR1 = 1;
4ExpandedBlockEnd.gif}

编译时出错(第2行):

illegal forward refrence

仔细一想,是因为VAR2引用的VAR1在VAR2之后定义,看来在Java中定义static变量时应遵循“声明先于使用”的原则。

 
二、static块

还是上一个类,VAR1和VAR2定义成final,值存在一个properties文件中,在使用前必须将值load进来:

System.getProperties().load(new FileInputStream("constants.properties"));

于是将上面的代码放在static块中:

ExpandedBlockStart.gif ContractedBlock.gif punlic final  class  Constants dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif  
staticdot.gif{
InBlock.gif    System.getProperties().load(
new FileInputStream("constants.properties"));
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
public static final int VAR2 = System.getProperties().getProperty("var2");
InBlock.gif
InBlock.gif  
public static final int VAR1 = System.getProperties().getProperty("var1");
ExpandedBlockEnd.gif}

None.gif
None.gif

但在运行时VAR1和VAR2没有被赋值,debug后发现static块根本没有执行。于是顿悟:final变量在编译时便被编译器计算、赋值,因此在运行时没有必要执行static块。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值