Mikhail_Bjornson Mikhail_Bjornson - 1 year ago 58
Java Question

Should static variables be used in a class that only gets instantiated once

I am creating a game in Java. I have this Director class which sets up my game thread and mostly deals with how the game operates. The class never should and is not instantiated more than once. Should the variables inside the class be static variables or not? I'm curious about what the java coding convention(if not every other object-orientated language) would be for something like this.


Answer Source

No, member variables shouldn't be static. The only thing relevant is that you need a single instance of Director class to manage your job, which could or couldn't be static according to your code.

Now, if you don't need access to Director instance from all around your code then you can just keep an instance somewhere, otherwise a singleton pattern could be useful. This is a pattern that manages a single instance of a class accessible from everywhere in your code.

Something like:

class Director {
  private static Director director;

  private Director() {

  public static Director getInstance() {
    if (director == null)
      director = new Director();

    return director;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download