Friday, May 8, 2009

Java Static Modifier

Static Modifier in Java:

In java we can have a Static Block, Static Variable, Static Method. Static modifier specifies that a variable or method is the same for all objects of a particular class. Some times we need a common variable or method for all objects of a part icular class. Typically, new variables are allocated for each instance of a class.

Variable declared as being static is only allocated once, regardless of how many objects are instantiated and all instantiated objects share the same instance of the static variable.
Similarly, a static method is one whose implementation is exactly the same for all objects of a part icular class. Static methods have access only to static variables.

Example of a static member variable and a static method:

static int refCount;
static int getRefCount() {
return refCount;
}
A beneficial side effect of static members is that they can be accessed without having to create an instance of a class. Static method or a variable is not attached to a particular object, but rather to the class as a whole. They are allocated when the class is loaded.

A static initializer block resembles a method with no name, no arguments, and no return type. It doesn't need a name, because there is no need to refer to it from outside the class definition. The code in a static initializer block is executed by the virtual machine when the class is loaded.

Example of a Static Block
static{
date1 = new Date();
for(int count = 0; count <>
var = var+1;
}
Static blocks are blocks defined within the body of a class using the static keyword but which are not inside any other blocks.

0 comments:

Blog Widget by LinkWithin

JS-Kit Comments

  © Blogger template Newspaper III by Ourblogtemplates.com 2008

Back to TOP