26/12/2013
JAVA Notes on
STATIC VARIABLES AND STATIC FUNCTIONS
Static Variable
If the variable is static, it means all the objects will share the same copy of the static variable.
In other words, if we make the variable non-static then all the objects will have separate copies of class variables where as static variable will have only one copy.
Static variable value may change during the ex*****on of the program.
More-over, Static Variable can be accessed without creating an object.
Example:
class Gabs1
{
int a;
static int b;
void set1( )
{
a=10;
b=20;
}
void set2( )
{
a=100;
b=200;
}
void show( )
{
System.out.println("Value of a and b is : "+a+","+b);
}
}
class Gabs
{
public static void main(String str[ ])
{
Gabs1 G1 = new Gabs1( );
Gabs1 G2 = new Gabs1( );
G1.set1( );
G2.set2( );
G1.show( );
G2.show( );
}
}
Static Function
If we make the function as Static ,then there are two restrictions on it.
a) Static functions can access only Static variables.
b) Static functions can call only Static functions.
In other words, Static function can interact only with Static variables and functions.
More-over Static function can be called without object of the class.
Program demonstrates what happens if Static function will interact with Static Variables or Functions.
class Gabs1
{
int a;
static int b;
void set1( )
{
a=10;
b=20;
}
static void set2( )
{
a=100;
b=200;
}
void show1( )
{
set1( );
set2( );
}
static void show2( )
{
set1( );
set2( );
}
}
class Gabs
{
public static void main(String str[ ])
{
System.out.println(“Example of Static Function”);
}
}