Java: Many-object variable ( static )

2019-02-21 18:25发布

问题:

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?

回答1:

Comment turned answer:

You're on the right track.

Currently, your static member will be increased with every worker you create. This means it will not hold a worker's ID (this can't be the case, as a static variable belongs to the class instead of individual instances), instead it holds the total number of workers you created so far.

Fix

  • Rename your static member to something like numWorkers so it reflects what it does
  • Introduce another (non-static) member, id (or workerId if you prefer)
  • Change workId++ to id = ++numWorkers

Why?

Now, every worker has their own id. You assign it by looking at the current number of workers created (numWorkers), increment that value by one, then assign it to id. This way, your first worker's ID will be 1, the second will be 2 and so on. numWorkers always holds the number of workers created, which is at the same time the last ID you handed out.


Put together

Since this question got quite some upvotes (= interest), I'll summarize the above into a blueprint:

public class Worker {
    private static int numWorkers; // Number of Worker objects created
    private int id;                // Individual ID of a worker

    public Worker() {
        id = ++numWorkers; // Will be 1 for the first, 2 for the second, ...
    }

    public int getID() {
        return id;
    }

    public static int getNumWorkers() {
        return numWorkers;
    }
}

Note that in Java, you don't need to initialize the primitive type int to 0, as that's the default value for an int. Of course, it is fine to do it anyway - it never hurts to be explicit.



回答2:

You are quite close to success actually.

Static members, as you may already know, belong to the class itself, not to each instance. But as you said, each worker should have his/her own unique ID, so workId should not be static.

However, we still need a static variable to keep track of what id should be given to the next worker we create. Let's declare one:

static private int nextWorkId = 0;

Then, in your constructor, you assign nextWorkId to workId, then increment nextWorkId:

workId = nextWorkId;
nextWorkId++;

You can also write it like this:

workId = nextWorkId++;


标签: java static