These are not mandatory rules, but it is better to follow them:
When to use static fields:
- Constants Best usage of static fields are constants, which shall be
final
too.
- ThreadLocals Most of the time you define thread-local variables static, otherwise you usually lose the reference to them. But don't forget to release their contents when there is no more use (or you will encounter memory leaks). Most of the time these variables are final too.
- And very rare cases when you shall keep a reference to a (semantically) singleton object which could be accessed from many places. (For example a reference to Hibernate
SessionFactory
in HibernateUtils).
Remember that, static fields shall usually be immutable during runtime of your application (they are sometimes modified during start-up and tear-down of the application).
When to use static methods:
- Helper utility methods that's the normal case, when a method does not depend on state of its containing object. These methods can be useful, and can be accessed without instantiating any object.
- Factory methods Factory methods are another good example of where to use static methods.
- Private methods which are not depend on objects state, when a private method just have no dependency on object's state, it is much better to define it
static
to gain a little performance.
- void main(String[]) method shall be static too.