Monday 16 January 2012

Static Variable(Class Variable) and Static Method(Class Method) In Java

Static Variable or Class Variable

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Student class, the instance variables are rollno, name, and dept. Each Student object has its own values for these variables, stored in different memory locations.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
For example, suppose you want to create a number of Student objects and assign each a roll number. This rollno is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Student objects have been created . Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfStudents, as follows:

class Student{
int rollno;
static int numberOfStudents;
Student(int rono){
rollno=rono;
numberOfStudents++;// increments one for each Student object creation.
}
static int getNumberOfStudents(){
return numberOfStudents;
}
}
class Main{
public static void main(String args[]){
Student s1=new Student(10);
Student s2=new Student(11);
System.out.println(Student.getNumberOfStudents());
}
}
The heap layout of above code is:

Properties of static variables
  • It is a variable which belongs to the class and not to object(instance).
  • Static variables are initialized only once , at the start of the execution.These variables will be initialized first, before the initialization of any instance variables.
  • By default static variables are initialized ( for int static variable zero,float 0.0 etc.).
  • We can initialize static variables using static blocks.
  • A single copy to be shared by all instances of the class.
  • A static variable can be accessed directly by the class name and doesn’t need any object.
  • Syntax : <class-name>.<variable-name>(e.g Student.numberOfStudents).

Static Methods or Class Methods

The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args)
Note:
You can also refer to static methods with an object reference like
instanceName.methodName(args);
but this is discouraged because it does not make it clear that they are class methods.
A common use for static methods is to access static fields. For example, in the above example

static int getNumberOfStudents(){
return numberOfStudents;
}

It is a method which belongs to the class and not to the object(instance).
Properties of static methods
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can  call only  other static methods and can not call a non-static method from it.
  • A static method  can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<method-name>
  • A static method cannot refer to "this" or "super"  keywords in anyway
  •  
Usage of Static variables and Static Methods  

1) Static variables can be used as data sharing amongst objects of the same class.
For example to implement a counter that stores the number of objects created at a given
time can be defined as so: 
public AClass
{
   static private int counter;
...
   public AClass()
   {
    ...
      counter += 1;
   }
...
   public int getNumberOfObjectsCreated()
   {
      return counter;
   }
}

The counter variable is incremented each time an object is created.

2) Public static variable should not be used, as these become GLOBAL variables that can be accessed from everywhere in the program. Global constants can be used, however. See below:
static public final String CONSTANT_VAR = "Const";
3) Static methods can be used for utility functions or for functions that do not belong to any particular object. For example:
public Match
{
 ...
   public static int addTwoNumbers( int par1, int par2 )
   {
        return par1 + par2;
   }
}

static block (How to initialize static variables)

The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM

class Test{
static {
//Code goes here
}
}
A static block helps to initialize the static data members, just like constructors help to initialize instance members .
 

1 comment: