When to use static methods

前端 未结 21 1959
旧巷少年郎
旧巷少年郎 2020-11-21 05:05

I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instanc

21条回答
  •  春和景丽
    2020-11-21 05:17

    A static method has two main purposes:

    1. For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.
    2. For the state that is shared by all instances of the class, like a counter. All instance must share the same state. Methods that merely use that state should be static as well.

提交回复
热议问题