Saturday, August 13, 2005

Static variables and methods

In Java, when a variable in a class is declared static, memory is allocated for the particular variable even when the objects are declared. They can be accessed when the objects are not created out of that particular class. In Java when memory allocation is done, there is separate memory space kept for the class itself. If there are static variables in the class then their values are stored here.

For eg.

public class abc {
static private int a;
private int b;
abc(int x,int y)
{
a=x;
b=y;
}
}

In the above class as one can access the variable a by accessing abc.a. One does not have to create an object to access them. Even as one create multiple objects of the class, the value of ‘a’ in all the objects are same since they point to the same memory location.

If there are static methods in a class, then the variables in them must be static since static methods can be called without declaring the object of the class. Due to this if there is any non-static variable in the static method and the static method is called without having declared an object then it will access a variable which does not have any memory allocated to it. In Java, the main method is always kept static since it is called without having declared any object.

For eg.

public class xyz {
static int x;
int y;
public static void main(String args[])
{
x=5;
//y=7; - error
}
xyz(int a)
{
y=a;
}
}

No comments: