I am new to object oriented coding and I have the following problem.
(note that this solution is part of my problem)
I need a variable that many objects can refer to, but keep some "private" information for each object. To be more specific, I created a class called Worker and I want every object of that class to have a unique ID of type int. So, first object has ID=1, second ID=2 etc... Note that I don't want just a random integer, whereas I need to start counting from 0 and increment...
Declaration and initialization of the variable in the class
static private int workId = 0;
and I tried to implement incremention by adding this line of code in the constructor body
workId++;
I instantiate some objects, add them to an ArrayList and using a for loop I print each object's variables.
System.out.println("Worker ID: "+workerList.get(i).getWorkerId());
and getWorkerId() (class method) consists of
public int getWorkerId () { return this.workId; }
Problem is my programm won't print every unique workID (because there isn't), but the last value of the static variable (which happens to be the number of objects).
Can you describe a solution to my problem?
workIdtonumWorkers, then introduce another member,private int id. Then, changeworkId++toid = ++numWorkers;- This way, every worker has a unique ID, the static field simply keeps track of the number of IDs given out (or, in other words, the last ID that was assigned to a worker).workerIdtoworkerCountand add a new variableworkerIdand set the value ofworkerIdin the constructor.