
正如其他人已经写过的,静态成员已绑定到该类,因此您需要在类级别上跟踪id,例如:
abstract class Parent { private int ID; Parent() { ID = nextId(); } abstract protected int nextId();}class Sub1 extends Parent { private static int curID = 0; protected int nextId() { return curID++; } //...}class Sub2 extends Parent { private static int curID = 0; protected int nextId() { return curID++; } //...}请注意,这种方法不是线程安全的-问题中的代码也不是。您不得同时从不同的线程从同一子类创建新对象。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)