java - Abstract class vs interface when sharing an attribute -


i have few classes same "level" in subtype hierarchy. need create id each instance , having parent class, containing static long , increment every instance of subclass.

75% of code subtypes same- made me prefer use abstract class (over interface) as:

1) can declare static variable id creator

2) can put code in parent class , share amongst subtypes

is correct? seem use interfaces. should use interfaces when subtypes need same methods, different implementations , when not need initialize attribute shared across subtypes (like id creator)?

i had been given impression colleagues interfaces preferred inheritance.

if have more 1 group of classes need id generation, wouldn't advise using inheritance because constrains reuse. in case why not build separate abstraction provides service of unique id generation? you'd give key , give id unique across invocations using same key.

public class idgenerator { private idgenerator() {} // no instantiation or subclassing private static final concurrentmap<string, atomiclong> ids = new concurrenthashmap<string, atomiclong>(); public static long id(string key) { atomiclong al = ids.get(key); if (al == null) { final atomiclong newl = new atomiclong(0); al = ids.putifabsent(key, newl); if (al == null) al = newl; } return al.getandincrement(); } } 

Comments

Popular posts from this blog

JQuery Autocomplete without using label, value, id -

c++ - Accessing inactive union member and undefined behavior? -

JAVA - what is the difference between void and boolean methods? -