Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Many-object variable ( static )

Tags:

java

static

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?

like image 934
Βαγγέλης Μαργέτης Avatar asked Apr 13 '17 14:04

Βαγγέλης Μαργέτης


People also ask

Can a static class have multiple objects?

This means that only one instance of a static member exists, even if you create multiple objects of the class, or if you don't create any. It will be shared by all objects. The static keyword can be used with variables, methods, code blocks and nested classes.

What is static {} in Java?

Definition and Usage. The static keyword is a non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class.

Can you have multiple instances of a static class in Java?

A static class is a nested class (i.e. it is declared within another class). It behaves like a top level class, which means you can create multiple instances of it.

Can we have multiple static block in Java?

Yes. It is possible to define multiple static blocks in a java class.


2 Answers

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.

like image 72
domsson Avatar answered Nov 15 '22 18:11

domsson


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++;
like image 24
Sweeper Avatar answered Nov 15 '22 16:11

Sweeper