-1

The main goal is to create a static variable that will increment with every new instance created of this class. Is this in anyway acceptable to use a static variable inside of a constructor? I know a static constructor would fall apart very fast, but any help is appreciated.

class Bird  {

    private static int birdPop = 0;

    public Bird (String birdColor, int birdAge) {
        setBirdColor(String n);
        setBirdAge(int g);

        birdPop++;
    }
}
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
JXN
  • 9
  • 4
  • 3
    Either this or do it within a static factory method. – Hovercraft Full Of Eels Feb 24 '20 at 21:32
  • This [question and its answers & comments](https://stackoverflow.com/questions/40597894/count-number-of-instances-of-a-class-in-multi-threading-environment) discuss the use of [AtomicInteger](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/concurrent/atomic/AtomicInteger.html), and mention using a factory class, "_what with mutable global state being pure evil_". – andrewJames Feb 25 '20 at 14:11

1 Answers1

0

Generally static variables are a bad idea, though you might get away with it in specialist circumstances.

Here it doesn't make sense for the population to be a static. The increment probably belongs in the instance method that creates the Bird in a given population.

It's also not thread-safe. The static variable has made the class thread-hostile instead of plain old thread-agnostic.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • The assignment specifically states to use a static variable that will increment with every created object. The idea was constructors are used to create and instantiate objects so I should just put the increment in there. (I'm still really new to this) What kind of method is a instance method, that is not a constructor? – JXN Feb 24 '20 at 21:40
  • 1
    @JXN I guess you've got to do whatever your assignment tell you to. An instance method is a method that is not static. – Tom Hawtin - tackline Feb 24 '20 at 21:41
  • Would anyone mind posting what a method such as "The increment probably belongs in the instance method that creates the Bird in a given population" would look like? – JXN Feb 24 '20 at 21:44