When to use static method and field?

后端 未结 6 795
难免孤独
难免孤独 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:31

    Static variables belong to a class, hence shared by all the objects, so memory usage is less if you really want the varible to be shared. If you declare the variable as public and static, then it is globally available for everyone.

    Static methods are generally the utility methods, depending on the access modifier, those can be used within a class or across the classes. Static utility class will help to reduce the memory usage again because you need not to create the object to call those methods.

提交回复
热议问题