When to use static method and field?

后端 未结 6 788
难免孤独
难免孤独 2020-12-05 22:02

I know what static is, but just not sure when to use it.

static variable: I only used it for constant fields. Sometimes there are tens of constants in a class, so us

6条回答
  •  甜味超标
    2020-12-05 22:24

    My personal rule of thumb is that static things are "just hanging out there". They are things that (disclaimer, not entirely true) are global, but make sense to include with this one particular class.

    Static fields are good if you find yourself loading some heavyweight objects repeatedly. For instance, the project I'm working on now has a toggle between two images. These are static fields that are loaded with the application and kept in memory, rather than reloading them every time and letting GC take care of the mess.

提交回复
热议问题