When to use static methods

前端 未结 21 1855
旧巷少年郎
旧巷少年郎 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:39

    Define static methods in the following scenarios only:

    1. If you are writing utility classes and they are not supposed to be changed.
    2. If the method is not using any instance variable.
    3. If any operation is not dependent on instance creation.
    4. If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
    5. If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.

提交回复
热议问题