As we know, with member variables of a class, if multiple objects are created, then every object will have its variable and changing variable of one object does not impact the variable of the other object.
class A
{
int i;
}
...
A a1 = new A();
A a2 = new A();
a1.i = 30;
a2.i = 50;
// LINE C
As shown above, at
LINE C
, the value of
a1.i
will be still
30
, since
a2.i
is different from
a1.i
.
But sometimes, it is necessary to have a variable, which is common across all the objects of a class. For
e.g.,, if we want to keep track of number of objects we created or the total amount in all accounts. We can use the
static
keyword to achieve this. The following program shows how.
Count Number Of Students
class CountStudents
{
public static void main(String s[])
{
Student st1 = new Student("Rajesh", 34, 'A');
Student st2 = new Student("Mahesh", 78, 'B');
System.out.println("Number of students after st1, st2 : " + Student.count);
Student st3 = new Student("Suresh", 65, 'A');
System.out.println("Number of students after st3: " + Student.count);
Student st4 = createStudent();
System.out.println("Number of students after st4: " + Student.count);
System.out.println("Print count using objects : " + st1.count + " " + st2.count + " " + st3.count + " " + st4.count);
}
public static Student createStudent()
{
return new Student("Akhilesh", 59, 'C');
}
}
class Student
{
// Static variable
static int count = 0; // LINE A
// Member variables
String name;
int marks;
char section;
Student(String name, int marks, char section)
{
this.name = name;
this.marks = marks;
this.section = section;
// Increment the static variable
count++; // LINE B
}
}
OUTPUTNumber of students after st1, st2 : 2
Number of students after st3: 3
Number of students after st4: 4
Print count using objects : 4 4 4 4
DESCRIPTIONHere we have a defined a Student
class with member variables name
, marks
and section
. We also included a static
or class variable called count
at LINE A
and incremented it in the constructor at LINE B
. Since the constructor is called when ever a new Student
is created, we can effectively keep track on the number of students using the static
variable count
. Also note that the static
variables can be accessed using the object variables like st1
, st2
or using the class name Student
. Either way, it points to the same class variable.
THINGS TO TRY
- Create one more
static
variable, all_students_marks
and add every students marks
in the constructor. Print the value of all_students_marks
at the end of the main method and it should be 236 (= 34 + 78 + 65 + 59)
.
- Remove the
static
keyword for count
at LINE A
and see what compilation errors do you get.
The other uses of the static keyword are explained in
Creating Static Methods In Java Using Static Keyword. Also checkout how the famous
Singleton Design Pattern In Java is implemented using the
static
keyword and the
private
constructor.