Skip to Content

Java static member variable example

  1. /*
  2.         Java static member variable example
  3.         This Java Example shows how to declare and use static member variable inside
  4.         a java class.
  5. */
  6.  
  7. public class StaticMemberExample {
  8.        
  9.         public static void main(String[] args) {
  10.                
  11.                 ObjectCounter object1 = new ObjectCounter();
  12.                 System.out.println(object1.getNumberOfObjects());
  13.                
  14.                 ObjectCounter object2 = new ObjectCounter();
  15.                 System.out.println(object2.getNumberOfObjects());
  16.                                
  17.         }
  18. }
  19.  
  20. class ObjectCounter{
  21.  
  22.         /*
  23.          * Static members are class level variables and shared by all the objects
  24.          * of the class.
  25.          *
  26.          * To define static member, use static keyword
  27.          * e.g. static int i=0;
  28.          *
  29.          * Please note that static member variables can be accessed inside
  30.          * non static methods because they are class level variables.
  31.          *
  32.          */
  33.         static int counter=0;
  34.        
  35.         public ObjectCounter(){
  36.                
  37.                 /*increase the object counter. Since only one varible is shared between
  38.                  * all objects of this class, it always return number of objects till now.
  39.                  */
  40.                 counter++;
  41.         }
  42.        
  43.         //returns number of objects created till now
  44.         public int getNumberOfObjects(){
  45.                 return counter;
  46.         }
  47. }