1、
public class Thing {
public Thing(int i) { ... }
...
}
Thing 实例没有提供任何可以获取其构造器参数的值的途径。因为Thing 是一个库类,所以你不具有访问其内部的权限,因此你不能修改它。假设编写一个称为MyThing 的子类,其构造器将通过调用SomeOtherClass.func()方法来计算超类构造器的参数。这个方法返回的值被一个个的调用以不可预知的方式所修改。最后,假设将这个曾经传递给超类构造器的值存储到子类的一个final 实例域中,以供将来使用:
public class MyThing extends Thing {
private final int arg;
public MyThing() {
super(arg = SomeOtherClass.func());
...
}
}
MyThing.java:
can't reference arg before supertype constructor has been called super(arg = SomeOtherClass.func());
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)。这个特征允许一个类中的某个构造器链接调用同一个类中的另一个构造器。在本例中,MyThing()链接调用了私有构造器MyThing(int),它执行了所需的实例初始化。在这个私有构造器中,表达式SomeOtherClass.func()的值已经被捕获到了变量i 中,并且它可以在超类构造器返回之后存储到final类型的域param 中。
2、
public class Creator {
public static void main(String[] args) {
for (int i = 0; i < 100; i++)
Creature creature = new Creature();
System.out.println(Creature.numCreated());
}
}
class Creature {
private static long numCreated = 0;
public Creature() {
numCreated++;
}
public static long numCreated() {
return numCreated;
}
}
Java 语言规范不允许一个本地变量声明语句作为一条语句在for、while 或do循环中重复执行。
该程序没有使用本地变量creature,所以改为:for (int i = 0; i < 100; i++) new Creature();即可
// Thread-safe creation counter
class Creature {
private static long numCreated;
public Creature() {
synchronized (Creature.class) {
numCreated++;
}
}
public static synchronized long numCreated() {
return numCreated;
}
}
// Thread-safe creation counter using AtomicLong;
import java.util.concurrent.atomic.AtomicLong;
class Creature {
private static AtomicLong numCreated = new AtomicLong();
public Creature() {
numCreated.incrementAndGet();
}
public static long numCreated() {
return numCreated.get();
}
}