Java Static vs Instance

Kezz picture Kezz · Aug 10, 2012 · Viewed 62.8k times · Source

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?

Answer

Kumar Vivek Mitra picture Kumar Vivek Mitra · Aug 10, 2012

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.