Static Members in java are of two types
1. static variables
2. static methods
when objects are defined to a class, each object contains a separate copy of instance variables of class.
The instance variables of one object differ from instance variables of another object.
In some situations we want to have common instance variables for all objects of same class.
This can be achieved by declaring the instance variables of class as "static" and such variables are called as
"Static Variables"
Example:
An instance variable is one per Object, every object has its own copy of instance variable.
public class Test{
int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have its own copy of x.
A static variable is one per Class, every object of that class shares the same Static variable.
public class Test{
public static int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have the exactly one x to share between them.
public class Foo
{
public int instanceVariable;
public int staticVariable;
}
Foo instance1 = new Foo();
Foo instance2 = new Foo();
instance1.staticVariable = 1;
instance1.instanceVariable = 2;
instance2.instanceVariable = 3;
instance1.staticVariable == 1 // true
instance2.staticVariable == 1 // true
instance1.instanceVariable == 2 //true
instance2.instanceVariable == 3 //true
Static methods access static variables, non static methods access non static variables
1. static variables
2. static methods
when objects are defined to a class, each object contains a separate copy of instance variables of class.
The instance variables of one object differ from instance variables of another object.
In some situations we want to have common instance variables for all objects of same class.
This can be achieved by declaring the instance variables of class as "static" and such variables are called as
"Static Variables"
Example:
An instance variable is one per Object, every object has its own copy of instance variable.
public class Test{
int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have its own copy of x.
A static variable is one per Class, every object of that class shares the same Static variable.
public class Test{
public static int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have the exactly one x to share between them.
public class Foo
{
public int instanceVariable;
public int staticVariable;
}
Foo instance1 = new Foo();
Foo instance2 = new Foo();
instance1.staticVariable = 1;
instance1.instanceVariable = 2;
instance2.instanceVariable = 3;
instance1.staticVariable == 1 // true
instance2.staticVariable == 1 // true
instance1.instanceVariable == 2 //true
instance2.instanceVariable == 3 //true
Static methods access static variables, non static methods access non static variables