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

前端 未结 13 1535
暖寄归人
暖寄归人 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 17:55

    My static methods are always one of the following:

    1. Private "helper" methods that evaluate a formula useful only to that class.
    2. Factory methods (Foo.getInstance() etc.)
    3. In a "utility" class that is final, has a private constructor and contains nothing other than public static methods (e.g. com.google.common.collect.Maps)

    I will not make a method static just because it does not refer to any instance variables.

提交回复
热议问题