Java: Static variables and methods

author-image
CIOL Bureau
Updated On
New Update
Apart from private, public and protected modifiers, there are other
modifiers in Java that are applicable on fairly higher grounds. Since we are discussing a
lot about modifiers, let us go through them from a panoramic point of view — later
on, when we delve deep into server side programming and sample project, they will gain
much more prominence.

Static variables

Typically, new variables are allocated for each instance of a class. For example, in
the highschool_student class, the variable group and the parent class variables name, age,
classroom etc. will be allocated for each instance of a class.

It is only because of this fact that we are able to store different set of variables in
different instances of a class. For example, ram may be one instance of highschool_student
class in which name=’ram’ and age=16 whereas rahim may be another instance in
which name=’rahim’ and age=17. It can be recollected that these two instances
may be instantiated as follows:

highschool_student ram = new highschool_student("ram", 16, 11);

highschool_student rahim = new highschool_student("rahim", 17, 12);

But, we may have situations in which we want to allot only one variable for all
instances of a class. For example, if we want to have the school name as another variable,
then it is evident that this school name is not going to change across all instances of
highschool_student class — is it not ? Then, why allot new variables to every
instance — we can as well have one variable that is shared by all instances of
highschool_student class. This is the most important inspiration behind static modifiers.

Static variables are those that are declared static during declaration. Thus, apart
from access modifier, you have one more modifier that defines the scope of the variable.
Take a look at the static string school_name in highschool student class code given
below.

Variables declared static are commonly shared across all instances of a class. When you
create multiple instances of highschool_student class — like ram and rahim, this
variable school_name is shared across all of them. Thus, at any given point of time, there
will be only one string value contained in the school_name variable.

Since there is only one copy of the variable available for all instances, the code
this.school_name will result in compilation errors — because it can be recalled that
this.variablename refers to the instance variable name. Thus, static variables are to be
accessed directly, as indicated in the code.

Static methods

Similar to static variables, even methods can be declared static. For example, the
accessor and mutator methods of highschool_student class have been declared static.

Static methods are those whose implementation is same for all instances of a class.
This means, there will be only one copy of the method that is running — which is
shared by all instances of the class. With this being the case, there is one interesting
constraint: static methods have access only to static variables!

For example, if you try to access the instance variable group inside a static method
(refer my code) it will result in this famous compiler exception:

Can't make a static reference to nonstatic variable group in class

This simply means that group is an instance variable which cannot be accessed by the
static method — whose common copy is shared across all instances.

Another interesting dimension of static modifiers and methods is that they can be
accessed even before instantiating a class! Take a look at the main method given in the
code example: Even before instantiating the ram class, the static variable school_name has
been set. Subsequently, when you try to construct several instances of highschool_student
class, like ram and rahim — this variable value is consistently maintained across all
instances of the class — which clearly proves that there is one copy of the
school_name variable that is shared.

Usage of static modifiers

Now, you might be wondering what is the practical implication of all this: in live
projects.

Typically, in live projects, there may be many variables which represent the runtime
environment of the project. A typical example of this will be the database you are going
to connect to, username and password.

All these variables can be declared static in one place (i.e. in one class) and can be
made use of by all other classes involved in database access. In this way, individual
classes need not maintain separate copies of the common variables.

Such environment variables are typically declared in a flat text file and are read into
memory during the initial invocation — in Java projects they are typically stored
with a .properties extension. We will take a detailed look at them later.

Source code of highschool_student .java (revised again !)

To compile this example type javac highschool_student.java

To run this example type java highschool_student

 public class highschool_student extends student {

//Additional attribute

protected String group;

protected static String school_name;

//Constructor method

public highschool_student(String name, int age, int classroom){

//Just referring to the parent class constructor method

super(name, age, classroom);

}

//Overloading Constructor method, with Group information

public highschool_student(String name, int age, int classroom, String group){

//Refer parent class constructor for basic attributes

super(name, age, classroom);

//Setting specific attribute of this class

this.group = group;

//this can also be done

//school_name = "APSV High school";

}

//static accessor and mutator methods !

public static String get_schoolname(){

return school_name;

}

public static void set_schoolname(String school_name1){

school_name = school_name1;

//this code will give error — this is not permitted inside
static methods

//this.school_name = school_name1;

//this code will give error — accessing instance variable inside static method !

//group = "B";

}

public String get_name(){

return name;

} 

public void set_name(String name1){

this.name = name1;

}

//Overriding the parent class method

public boolean learning (String explanation){

//just a simple reply

if ((explanation.length() > 0) && (explanation != null))

return true;

else

return false;

}

//Overloading the learning method

public boolean learning (String explanation, String lesson){

//just a simple reply

if ((explanation.length() > 0) && (lesson.length() >0))

return true;

else

return false;

} 

public void lab_experiment (String experiment){

//implmenet the experiment process

//no need to return anything

} 

public static void main(String argv<>){

highschool_student.set_schoolname("APSV High School");

System.out.println("School Name :" +
highschool_student.get_schoolname()); 

highschool_student ram = new highschool_student("ram", 16, 11);

System.out.println("Ram's School Name :" +
highschool_student.get_schoolname());

}

}

S Gokul is an e-commerce Consultant with Cybervalley Global Systems,
India.

This article originally appeared in CIOL on March 2001.

tech-news