首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

私有构造器擒获 (private constructor capture)

2012-12-19 
私有构造器捕获 (private constructor capture)java puzzler 53?? 下面的代码编译失败,提示:Cannot refer

私有构造器捕获 (private constructor capture)

java puzzler 53

?? 下面的代码编译失败,提示:Cannot refer to an instance field arg while explicitly invoking a constructor

?

class SomeOtherClass {static int func() {return Math.round(12L);}}public class MyThing extends Thing {private final int arg;public MyThing() {this(SomeOtherClass.func());}private MyThing(int i) {super(i);arg = i;}}

?

这个方案使用了交替构造器调用机制(alternate constructor invocation)

在这个私有构造器中,表达式SomeOtherClass.func()的值已经被捕获到了变量i中,并且它可以在超类构造器返回之后存储到final类型的域arg中。

热点排行