Reputation: 21
I have a variable in another class for an id in java. I want it to start from 0 and increment every time afterwards that the new id will be 1 and so on.
I got the idea of declaring a new variable called id
in the main class, every time I create a new object I will call the method setId
with the new id and then increment the variable again. But is there another way to do it? (keep in mind the constructor for the class dose not have ID and I can't change the constructors)
Upvotes: 1
Views: 4915
Reputation: 838
Let's say your class is called Main and looks like this.
public class Main {
// Some code by you
}
You can now use static variables (which means they are member of the class itself not of each single instance of it). If you are not familiar with static variables I would recommend you to read something like this.
We now add a static variable named counter
to your class:
public class Main {
private static int counter = 0;
// Some code by you
}
Now we need to increment this variable in every constructor of the class, in this example just the default one:
public class Main {
private static int counter = 0;
public Main() {
counter++;
}
// Some code by you
}
You can now use this static variable and set it as your id.
Upvotes: 2