Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
Java: Many-object variable ( 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?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Santiago Trujillo Relatório

0

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++;
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda