Static Keyword
Basically, it is used to define the class member. It represents the group property of the class member. The static keyword is four different uses in the class
-
Static variable
-
Static block
-
Static method
-
Static class (inner class)
Static Variable
It is used for a single copy of a static member created during class loading. The static member gets only a single allocation in the class area at the time of class loading.
Code Example
class A
{ static int var=7; // class member
public static void main(String arg[])
{ A obj1=new A();
A obj2=new A();
System.out.println("first object1 = "+obj1.var);
System.out.println("second object2 = "+obj2.var);
}
}
Static block
The class's static member is initialized using it. This block is executed just after class loading. It has loaded before the main method at the time of class loading.
Code Example
class block{
static
{
System.out.println("static block");
}
public static void main(String arg[])
{
System.out.println("main method");
}
}
Static method
The static keyword is used with the method name called static method. The static method cannot be used instance variable. It is used to access static data members and modifies their value of it. Non-static values can be accessed via the object of the class. But the static technique is subject to several limitations.
-
The static method is unable to directly access non-static variables or methods.
-
Static keywords cannot override any variable or method.
-
Static cannot be used with this and the super keyword.
Code Example
class A
{
static int a;
public static void display()
{
a=5;
System.out.println("static method "+a);
}
public static void main(String arg[])
{
System.out.println("main method");
A b=new A();
b.display();
}
}
RANREV INFOTECH