I have a few classes which are the same “level” in a subtype hierarchy. I need to create an ID for each instance and I usually do this by having a parent class, containing a static long and I just increment it for every instance of the subclass.
75% of the code for the subtypes is the same- this made me prefer to use an abstract class (over an interface) as:
1) I can declare a static variable for the ID creator
2) I can put the code in the parent class and share it amongst the subtypes
Is this correct? I seem to rarely use interfaces. Should I only use interfaces when subtypes need the same methods, but different implementations and also when I do not need to initialize an attribute to be shared across the subtypes (like the ID creator)?
I had always been given the impression from colleagues that Interfaces were preferred to inheritance.
If you have more than one group of classes that need ID generation, then I wouldn’t advise using inheritance because it constrains reuse. In that case why not build a separate abstraction that provides the service of unique ID generation? You’d give it a key and it would give you an ID that is unique across all invocations using the same key.