简体   繁体   English

在抽象类上实现ID的一种优雅方法

[英]A elegant way to implement ID on a abstract class

I have an abstract class. 我有一个抽象类。 I want that every instance has a unique ID. 我希望每个实例都有唯一的ID。 I have implemented: 我已经实现了:

public abstract class MyAbstractClass{

    static AtomicInteger nextId = new AtomicInteger();
    private int id;

    public MyAbstractClass() {
        id = nextId.incrementAndGet();
    }
}
public class MyClass extends MyAbstractClass {

       public MyClass(){
             super();
       }
}

This approach works except the part there is nothing forcing the subclass to call the constructor. 除了没有什么可以强迫子类调用构造函数的部分以外,此方法有效。

Is there a way to implement a global ID for an abstract class? 有没有一种方法可以为抽象类实现全局ID?

there is nothing forcing the subclass to call the constructor. 没有什么可以强迫子类调用构造函数。

There is nothing you can do to stop the subclass from calling super() unless parent constructors are built hierarchically wrong. 除非父构造函数在层次结构上错误构建,否则您无法阻止子类调用super()

By "hierarchically wrong", I meant there is a parent constructor that isn't based on its no-argument constructor. 所谓“层次错误”,是指存在一个不基于其无参数构造函数的父构造函数。 For instance, 例如,

public MyAbstractClass() {
    id = nextId.incrementAndGet();
}

public MyAbstractClass(String s) {
    // ignores to call this();
}

Otherwise, any child will eventually call super() , and, thus, trigger your id initialisation. 否则,任何孩子最终都会调用super() ,从而触发您的id初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM