Wednesday, June 3, 2015

Static Variables and Methods in Java

In place of global variables as in C/C++, Java allows variables in a class to be declared static:
 public class A 
 {
   static int k_var;
  }
A single memory location is assigned to this variable and it exists and is accessible even when no instances of class A are created.
These static variable is also called class variables, since they belong to the class as a whole.
If a class property is also declared final, then it becomes a global constant (i.e. can't be altered):
  public class A
 {
    final static int k_var;
 }
Similarly, methods can also be declared static, and are called class methods
  public class A {
   static void A_method(float x){ }
  }   
These class methods also can be called even when no instance of the class exists. The code in a class method can only refer to static variables and the argument variables.

No comments: