I have an abstract class called Worker
which is extended by two subclasses, PermanentWorker
and NonPermanentWorker
. All these classes inherit various properties, one of those being wCode
, an int that should be given to every new worker automatically when it is created. For example, the first worker should have wCode=XXX1
, the second wCode=XXX2
etc. (XXX being some three digit number like 123, doesnt matter)
The question is, how do I check if an object has already been created (or not) so that it will receive the appropriate code? Like it's obvious that an if-else command block should be used, but how exactly? My original approach was something like this:
public abstract class Worker
{
private int wCode;
[....]
public Worker() {
int i=1;
if(....) wCode = 1230 + i;
i++; }
public abstract class Worker {
private static int lastId = 0;
protected final int wCode;
public Worker() {
wCode = lastId++;
}
}
You need a static field which will be your ID generator. wCode
is going to be initialized in the worker class and you don't have to worry about an ID being already used because it won't happen.
If you really need to keep track of Worker
s and retrieve them, you can store them in a Set<Worker>
static field or a Map<Integer, Worker>
and add them in the constructor.
e.g.
public class Worker {
// rest of the code omitted
// workers set
private static Set<Worker> workersSet = new HashSet<>();
// or workers map
private static Map<Integer, Worker> workersMap = new HashMap<>();
// add the instance to the set or map
public Worker() {
// id part omitted
workersSet.add(this);
// or
workersMap.add(this.wCode, this);
}
// expose the collections as read-only to outside world
public static Set<Worker> workers() {
return Collections.unmodifiableSet(workersSet);
}
public static Worker getWorker(int wCode) {
return workersSet.stream()
.filter(w -> w.wCode = wCode)
.findAny()
// or drop the orElse part and make the method return Optional<Worker>
.orElse(null);
// for map counterpart, it's easier:
// return workersMap.get(wCode);
}
}
An easier implementation would be with an List
/ArrayList
instead of Set
/HashSet
and the retrieval would be as easy as workersList.get(wCode);
since the Worker
with wCode
set to 50 will be found at index 50 in that list.