In java the static keyword leads to following important concepts , namely
1) Static Variable
2) Static Block
3) Static Method
Static variables are the special type of variable which are created during the load time of class, or we can say when the class is instantiated. The syntax for declaring variable as static is as follows,
Some important points regarding static variables are
- It should be accessed by class name.
- Only one instance is created and it is shared by all the data members.
This can be further explained as follows . Consider an example consisting of static and Non static member
In above example when class is instantiated multiple copies of instance variable k is created where each copy would going to point a particular object at a time, but in case of static only one copy is created and shared among all objects & methods. As shown in fig
Static Block:Static block’s are the block which are implicitly called when the class is instantiated that means when the instance of class is made. (by using new operator)
When the above program is executed , for each instance of class StaticBlockDemo static block is called , but keep in mind it is called only when the class is instantiated, not declared.
Some points about Static method are
- Static methods are automatically created during load time of class.
- They are accessed by using class name.
- A single copy of static method is created and is shared among all other methods.
- The most important point “Static function cannot access non static methods/memeber”.
Declaration of static method is given as follows