Friday, October 9, 2015

Java understanding static




Example to illustrate static in Java

In this example the variable counter is a static variable and it is a class variable not a instance variable. The number of times the counter() method is instantiated which in turn executed the println statement and incremented the static variable counter by 1. As the static variable does not belong to instance of a class instead it belongs to a class instead, so every time the counter() method is instantiated the counter gets incremented.

 package sudas.study.example.one;  
 public class ObjectCounter {  
      public static void main(String[] args) {  
           ObjCounter o1 = new ObjCounter();  
           o1.counter();  
           ObjCounter o2 = new ObjCounter();  
           o2.counter();  
           ObjCounter o3 = new ObjCounter();  
           o3.counter();  
      }  
 }  
 class ObjCounter {  
      static int counter = 0;  
      public void counter() {  
           System.out.println("Number of object created " + counter++);  
      }  
 }  

No comments:

Post a Comment