Java Static vs Instance
So my coder friend hates using the static
coding. Yet my Java program is full of it to link between classes, and I have a lot of them!
Is it worth rewriting the whole code to remove the static method?
Is there any advantage of using one over the other?
1. An instance variable is one per Object, every object has its own copy of instance variable.
Eg:
public class Test{
int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1
and t2
will have its own copy of x
.
2. A static variable is one per Class, every object of that class shares the same Static variable.
Eg:
public class Test{
public static int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1
and t2
will have the exactly one x to share between them.
3. A static variable is initialized when the JVM loads the class.
4. A static method
cannot access Non-static
variable or method.
5. Static methods
along with Static variables
can mimic a Singleton Pattern
, but IT'S NOT THE RIGHT WAY, as in when there are lots of classes, then we can't be sure about the class loading order of JVM, and this may create a problem.
static
is for the cases where you don't want to have copy for each instance
instance
variables are for the cases where you want separate copy for each instance of object.
Based on business cases, which one to use may change.