读书人

私有构造器擒获 (private constructo

发布时间: 2012-12-19 14:13:14 作者: rapoo

私有构造器捕获 (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中。

读书人网 >编程

热点推荐