Unit 2 (Prog 6) : Test Static Keyword

By | June 9, 2013
This article covers basics of static keyword, static methods and static variables.

/*
 * STATIC METHODS :
 * 1. Static method can not access non-static (Instance) variable or method.
 * 2. Static method can not be overridden they are redefined.
 */

class CountExample {
   static int count1;
   int count2;
   CountExample() {
      count1 += 1;
      count2 += 1;
   }

   String printValues(Object obj) {
      return "From " + obj.getClass().toString() + "Value of Count1 : " + count1 + "nValue of Count2 : " + count2;
   }
}

public class StaticDemo {
   int i = 5;
   public static void main(String a[]) {
      // Accessing static variable or method will not effect on its behavior.
      CountExample ce1 = new CountExample();
      ce1.count1 = 5;
      ce1.count2 = 10;
      CountExample ce2 = new CountExample();
      ce2.count1 = 5;
      ce2.count2 = 10;
      CountExample ce3 = new CountExample();

      System.out.println(ce1.printValues(ce1));
      System.out.println(ce2.printValues(ce2));
      System.out.println(ce3.printValues(ce3));
   }
}

One thought on “Unit 2 (Prog 6) : Test Static Keyword

Leave a Reply

Your email address will not be published. Required fields are marked *