Is there a rule of thumb for when to code a static method vs an instance method?

前端 未结 13 1658
暖寄归人
暖寄归人 2021-02-04 17:19

I\'m learning Java (and OOP) and although it might irrelevant for where I\'m at right now, I was wondering if SO could share some common pitfalls or good design practices.

13条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 18:20

    If you keep state ( a value ) of an object and the method is used to access, or modify the state then you should use an instance method.

    Even if the method does not alter the state ( an utility function ) I would recommend you to use an instance method. Mostly because this way you can have a subclass that perform a different action.

    For the rest you could use an static method.

    :)

提交回复
热议问题