Java和继承的静态成员

Java和继承的静态成员,第1张

Java和继承的静态成员

正如其他人已经写过的,静态成员已绑定到该类,因此您需要在类级别上跟踪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++;    }    //...}

请注意,这种方法不是线程安全的-问题中的代码也不是。您不得同时从不同的线程从同一子类创建新对象。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5489038.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存