Example & Tutorial understanding programming in easy ways.

What’s difference between Static and Non-Static fields of a class?

1) Difference between Static and Non-Static fields of a class is that you can call static method without creating any object e.g. Collections.sort(). This makes static method useful utility.

while you need to instantiate an object to call non static method in Java. Static methods are also pretty useful on several design pattern including Factory and Singleton.

2) You can not access a non static variable inside any static method in Java.

but  you can access static variables or call static method from a non static method without any compile time error.

3) One more worth noting difference between static and non static method is that you can not override static method in Java. They are bonded during compile time using static binding. Though you can create a similar static method in sub class, that is know as method hiding in Java.

4) static methods are known as class methods, if you synchronize static method in Java then they get locked using different monitor than non static methods e.g. both static and non static methods are locked using different monitor in Java, and that's why its grave Java mistake to share a resource between static and non static method in Java.

5) Static methods are commonly used inside utility classes e.g. java.util.Collections or java.util.Arrays, because they are easier to access, as they don't need an object. One of the popular example of static method is though main method, which act as entry point for Java programs.

Example:

public class Test {

static int a=6;

int b=8;

public static void main(String[] args) {

Test obj1=new Test();

Test obj2=new Test();

obj1.a=10;

obj2.a=12;

obj1.b=24;

obj2.b=36;

System.out.println("Static a"+obj1.a); //12

System.out.println("Static a"+obj2.a); //12

System.out.println("Static a"+a); //12

System.out.println("Static b"+obj1.b); //24

System.out.println("Static b"+obj2.b); //36

}

}

 

Read More →