Until few weeks back, I thought I understand when to make fields and methods static
or non-static
. For example, when a field (say object of another class) is unique for any number of objects for the class, it should be made static
.
But then I read about JVM garbage collection a few weeks back.
I understand that static
fields are never garbage collected and remain in memory all along, unless the class loader itself is garbage collected.
But if I don't make that field static
, at least it will be garbage collected.
So, it seems there is a very thin line between making fields/methods static or not.
Can anybody please explain to me this thin line in deciding, so that my application is way more efficient.
In the static method, the method use compile-time or early binding. For this reason, we can access the static method without creating an instance. In a non-static method, the method use runtime or dynamic binding. So that we cannot access a non-static method without creating an instance.
nonstatic in British English (ˌnɒnˈstætɪk ) adjective. computing. (in computer languages) not static.
An example of static is rubbing a balloon on one's hair and then have the balloon stick to a wall. adjective. 1. (electricity) Of, relating to, or producing stationary charges; electrostatic. adjective.
Non static variables are specific to that instance of a class. Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.
It might be thin but there is very clear distinction. You declare a field as static when it is not at all related to any instance of a class.
A simple usecase of static field is declaring constants using final
keyword, e.g.:
public static final int MAX_ALLOWED = 10;
Same is the case with methods also. You declare a method as static when it is not dependent on instance of a class OR the state of the class. That's the reason a static method cannot use instance members of a class.
These are not mandatory rules, but it is better to follow them:
When to use static fields:
final
too.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:
static
to gain a little performance.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With