Java static methods pros & cons

后端 未结 4 1316
长情又很酷
长情又很酷 2021-02-08 10:46

I havent used a lot of static methods before, but just recently I tend to use more of them. For example if I want to set a boolean flag in a class, or acess one without the need

4条回答
  •  轮回少年
    2021-02-08 10:57

    In general, by making finished static like that you create a situation where there can only be one instance of your MainLoop class executing run at any one time. If there is more than one instance then setting finished will end them all -- not what is usually desired.

    However, in this particular scenario, where you want to "end application", presumably meaning you want to end all instances of MainLoop, the approach may be justified.

    However, the number of situations where this approach may be merited are few, and a "cleaner" way to handle this scenario would be to keep a static list of instances and work through the list, setting the instance variable finished in each instance. This allows you to also end individual instances, gives you a natural count of existing instances, etc.

提交回复
热议问题