Should Java methods be static by default?

后端 未结 23 1277
既然无缘
既然无缘 2020-12-04 09:24

Say you\'re writing method foo() in class A. foo doesn\'t ever access any of A\'s state. You know nothing else about what foo does, or how it behaves. It cou

23条回答
  •  悲&欢浪女
    2020-12-04 09:52

    I think "private static" (edit: for methods) is kind of an oxymoron in Java. The main point of static methods in my mind is to provide access to functions outside of the context of object instances. In other words, they're practically only ever useful if they're public. If you're only calling a method from within the context of a single object instance, and that method is private, it makes no sense to make it static. (edit: but, it makes no practical difference).

    In this sort of case, I usually try to make the methods abstract enough that they're useful in other contexts, and I make them public in a utility class. Look at it as writing supporting library code, and think hard about your api.

提交回复
热议问题