I need a class which creates Objects assigning an ID to each Object created. This ID is as usual an int attribute to the class. I want this value (ID) to be increased each time an Object is created and then to be assigned to that Object starting with 1. It strikes me that I need a static int attribute.
How can I initialize this static attribute?
Should I create a separate method to do the increment of the ID (as an ID generator) which is invoked inside the constructor?
What is in general the most effective and well-designed manner to implement that?
Just like you mention use a
static intfor the id, and increment it when creating new objects.Please note that you need to protect
counter++ifMyObjectis created by multiple threads (for example usingAtomicIntegeras the other answers suggest).