1

I have an abstract class. I want that every instance has a unique 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?

1 Answers1

2

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.

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • Did you mean the abstract class having more than one constructor? – Matheus Popst de Campos Aug 06 '19 at 22:18
  • Is it still called *default constructor* when you've implemented it with your own code (i.e. no longer default)? – RaminS Aug 06 '19 at 22:19
  • @MatheusPopstdeCampos If it had, you would need to make sure each constructor calls the default one (`this();` as the first line in the body of a parent constructor) – Andrew Tobilko Aug 06 '19 at 22:21
  • @Gendarme I am not sure I got you correctly. Any child constructor will call a parent constructor. Any parent constructor will call the default constructor. Does it make more sense? – Andrew Tobilko Aug 06 '19 at 22:26
  • I'll rephrase. Is the parameterless constructor (which always exists) called *default constructor* even when you implement it (override it?) in your code (since it's arguably no longer default)? [This answer](https://stackoverflow.com/a/4488766/5221346) suggests that it isn't. – RaminS Aug 06 '19 at 22:36
  • 1
    @Gendarme edited to "no-argument constructor", it's more accurate, is it? – Andrew Tobilko Aug 06 '19 at 22:47