1

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)

Broken_Window
  • 2,037
  • 3
  • 21
  • 47
Foy
  • 21
  • 1
  • 5
  • 4
    Make a static class variable and increment it in the constructor. Although this seems like a hacky way to implement UUID. – sleepToken Mar 10 '20 at 13:33
  • https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class recommended reading – Adder Mar 10 '20 at 13:36
  • @sleepToken sadly i can't change the type of it it is set at private and i can't change it into static – Foy Mar 10 '20 at 13:38
  • In the context of a databae you can leave it to the database and use ResultSet.getGeneratedKeys to retrieve the new ID. – Joop Eggen Mar 10 '20 at 13:40

1 Answers1

2

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.

ich5003
  • 838
  • 1
  • 9
  • 24
  • OP says he doesn't have access to the constructor. Try something like: public static int counter = 0; public int id = counter++; – Design.Garden Mar 10 '20 at 13:42
  • thanks i got a way with it and it worked thanks a lot my dude i did it like this this.Id = IdGenerator++; – Foy Mar 10 '20 at 13:46
  • I'm happy I could help you with you question. If your question is answered I would appreciate if you mark this answer as accepted. (The green checkmark next to my answer) – ich5003 Mar 10 '20 at 13:48