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

java puzzler 53java

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

 

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是一个库类,只提供有参数的构造器,没有提供任何访问器,你不具备访问内部的权限,所以不能修改它。code

这时,想编写一个子类,其构造器经过条用SomtOtherClass.func()方法来计算超类构造器的参数。这个方法的返回值能够在一次次调用中返回不一样的值,你想将这个传递给父类的值保存在子类的一个final实例中。因而有了上面的代码,可是不能编译经过。ci

 

修改it

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)io

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