Sunday, 22 July 2012

Static Members


STATIC MEMBERS:
A Class basically contains two sections. One declares variables and other declares methods. These variables and methods are called instance variables and instance methods. Whenever an object is created a new copy of each instance variables and methods has been created, and there is no link between the two objects, as any changes in one copy has no effect on the another.

But there may be times, when you want to define a class member that may be used independently of any object of its class, means that defining a class member that is common to all the objects and accesses without using a particular object.

In this case the member belongs to the class as a whole rather than the objects created from the class. Such members can be created using the static keyword as follows.

static int a=4;
static int b=5;
static int box(int x, int y);

Thus, the members that are declared static are called static members of the class, and are associated with the class itself rather than individual objects. The static variables and static methods are often referred to as class variables and class methods in order to distinguish them for their counterparts, instance variables and instance methods.

The most common example of a static member is main(). Main() is declared as static because it must be called before any objects exists.

Methods declared as static have several retsrictions:
  1. Static methods can only be called up by static Methods.
  2. Static methods must only access static data.
  3. Static methods can not refer to this or super in anyway.
Let us consider an example showing the operations on static members.

Class StaticExample
{
static float add(float a, float b)
{
return a+b;
}
{
static float sub(float a, float b)
{
return a-b;
}
{
static float mul(float a, float b)
{
return a*b;
}
static float divide(float a, float b)
{
return a/b;
}
}

class CallstaticMember
{
float x= Static Example.add(4.0 , 5.0);
float y= Static Example.sub(7.0 , 3.0);
float z= Static Example.mul(a , b);
float w= Static Example.divide(z , y);
system.out.println(“w =” +w);
}
}

The output of the above stated example is as follows:
w = 9.0

In the above program, we had created four static methods and called up them outside of the class in which they are defined. A static variable can be accessed in the same way as the instance method, by the use of the dot operator an the name of the class in place of object name of the class.