Tuesday 10 September 2013

What is Static Keyword?

In Java,Static Keyword is associated with the class not with the instance of class.Therefore you can access static member without creating a class instance.
There are two types of static members in C++ and Java:
1.Static field:
The value of static field remains same for all the instance of the class.You can interchange the position of static keyword as per your need.Between the function calls its value remains same.
1.1Like: public static int a ;
1.2 static public int a;
Both the statement is same 1.1 and 1.2
If a class has static field StudentId all the objects within the class will have same value for StudentId in the program.It will help in counting the number of objects.
Static field will be accessed by classname.
classname.<static variablename>.
  
Static fields are created and initialized when the class is first loaded.

2.Static Method():
A method declares as static becomes static method which can access only static variables.
Static method is associated with the class not with the instance or object of the class.
Static method we see in our program that is main()which is called by the java runtime to execute an application.
In order to call static method:
classname.staticmethodname();///Sytax for call static method.

Simple Program in Showing USe of Static:
class A
{
int a =10;
static int b=10;
void display()
{a=a+a;
b=b+b;
System.out.println("a");
System.out.println("b");
}
}
public class C
{
public static void main(String args[])
{
A d=new A();
d.display();
A e=new A();

e.display();
}

OUTPUT:
20
20
20
40

No comments:

Post a Comment