Monday, 30 January 2012

static keyword in Java

•When all the objects of a class have to access common information, such information is stored in “static” variables.
•“static” members in a class are accessible without creating any objects.
•“static” members are accessed directly using the “class name”.
•Within a class, members can be declared with the keyword “static”. So within a class there can be:
1) static variables (class variables)
2) static methods (class methods)

“static” variables:
•“static” variables can be treated as global variables.
•“static” or class variables are shared by all the objects of a class.
•Each object does not have its own copy of the static variable.
•Syntax for declaring a static variable is as follows:
static data-type variable-name;

Example:
class Box
{
    static int sides;
    int length, width, height;
}

“static methods”:
•Methods declared as static has three restrictions. They are:
1) static methods can call other static methods only.
2) static methods can access only static variables.
3) “this” and “super” cannot be used in static methods.
•Syntax for declaring a static method:
static return-type method-name(parameters)
{
   statement(s);
}


•Example on static method:
class Box
{
   int length, width, height;
   static int sides;
   static void setSides()
   {
     sides = 6;
   }
}

Accessing static members:
•“static” members in a class can be accessed directly using the class name as shown below:
class BoxDemo
{
   public static void main(String args[])
   {
     Box.sides = 10;
     Box.setSides();
   }
}

In the above program, both sides and setSides() are static members of the Box class. So, they can be accessed directly using the class name.

2 comments: