初始化接口中的字段

接口中定义的字段会自动具有static 和final 属性。它们不能是“空白final”,但可初始化成非常数
式。例如: 
 
//: RandVals.java 
// Initializing interface fields with  
// non-constant initializers 
import java.util.*; 
 
public interface RandVals { 
  int rint = (int)(Math.random() * 10); 
  long rlong = (long)(Math.random() * 10); 
  float rfloat = (float)(Math.random() * 10); 
  double rdouble = Math.random() * 10; 

} ///:~ 

 
由于字段是 static的,所以它们会在首次装载类之后、以及首次访问任何字段之前获得初始化。下面是一个
简单的测试: 
 
//: TestRandVals.java 

 
public class TestRandVals { 
  public static void main(String[] args) { 
    System.out.println(RandVals.rint); 
    System.out.println(RandVals.rlong); 
    System.out.println(RandVals.rfloat); 
    System.out.println(RandVals.rdouble); 
  } 
} ///:~ 
 
当然,字段并不是接口的一部分,而是保存于那个接口的 static存储区域中。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值