March 21, 2011

Effect of static keyword on variables and methods in Java

Effect of static on variables


The static keyword can be applied to instance variables and cannot be applied to local variables. Marking an instance variable as static makes its cease to be an instance variable and become a static variable.


There is exactly one copy of the static variable irrespective of the number of objects of that class (0 to n) and the static variable can be accessed on the class name.


Sometimes, static variables are also referred to as class variables.

public class Test {

   private static int i;

   public void m1() {
      System.out.println("static i = " + Test.i);
   }

   public static void m2() {
      System.out.println("static i = " + Test.i);
   }    
}


Effect of static on methods


The static keyword can be applied on instance methods. Just as with instance variables, application of the static keyword on an instance method makes it cease to be an instance method and become a static method.


A static method can be invoked on the class name irrespective of the objects of that class. Static methods within a class can access static variables only, accessing instance variables directly from a static method is not allowed.


However, instance variables can be accessed from within a static method via an object reference variable.


For more example of member access from a static method/context, refer - http://www.javaissues.com/2011/02/access-issues-from-static-context-in.html

public class Test {

   int i;
   static int j;
     
   public static void m1() {
      System.out.println("Method m1");
      i = 3;       // not allowed, will not compile
      j = 2;       // allowed

      Test t = new Test();
      t.i = 3;     // now i can be accessed
   }
}

No comments:

Post a Comment