java puzzler 53
下面的代码编译失败,提示:Cannot refer to an instance field arg while explicitly invoking a constructor
package arkblue.lang.javapuzzler.n53;
class Thing {
public Thing(int i) {
}
}
public class MyThing extends Thing {
private final int arg;
public MyThing() {
super(arg = Math.round(12L)); //编译失败
}
}
假设Thing是一个库类,只提供有参数的构造器,没有提供任何访问器,你不具有访问内部的权限,因此不能修改它。
这时,想编写一个子类,其构造器通过条用SomtOtherClass.func()方法来计算超类构造器的参数。这个方法的返回值可以在一次次调用中返回不同的值,你想将这个传递给父类的值保存在子类的一个final实例中。于是有了上面的代码,但是不能编译通过。
修改
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中。