Prev Next
- Generally, a member declared in a class can only be accessed through the object of that class. But, declaring a member as static means that it can be accessed without creating object and it belongs to the class and not to the instance.
- The keyword ‘static’ can be applied to variable, method, block and nested class.
Static Variable (class variable):
- Static variable is initialized only once.
- A single copy is created and shared by all the instances of the class. It can be accessed without using object.
- A static variable can be accessed outside of the class using the following
syntax:
Classname.static_variable |
Static Method:
A static method belongs to the class rather than the instances of the class. There are some restrictions over static methods. They are,
- A static method can directly call only static methods
- It can directly access only static fields
- It cannot use ‘this’ and ‘super’ (since these keywords (this and super) are used to access a particular object, they cannot be used for static contents as they are class specific, not object specific)
Static method can be invoked using the following syntax
Classname.static_method(); |
Static Block:
Static blocks are executed when the class gets loaded even before any other method in the class. Initializations of variables and other startup procedures can be defined in a static block since it is first block executed when a class gets loaded.
That’s why the main method is declared as ‘static’ as mentioned in previous chapters.
Syntax:
static { //statements } |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class StaticDemo { static int a = 0, b = 10; //static variables static void display() { //static method System.out.println(“a:”+a+”\t”+”b:”+b); } public static void main(String args[]) { static { //static block, first executed staticDemo.a = 5; //accessing static fields staticDemo.b = 10; } System.out.println(“Hello”); StaticDemo.display(); //invoking static method } } |
Output:
Hello a=5 b=10 |