Static Keyword : Introduction
- There will be time when you want a class member to be common to all the object of the class, i.e. all the objects of the class will share that member.
- Here static keyword comes into play.
- To access any member of the class it is done by using object with (.) operator.
- But static keyword before any class member makes it independent of the object.
Static Keyword : The Discussion
- Static keyword can be applied to a :
- Let us discuss them one by one along with their respective syntax and examples.
1) Static variable
- A variable preceded with static keyword is called static variable. Static variable is common to all class objects.
- Static variable is independent of the objects hence is accessed using class name rather then object name.
- The above diagram show that static variable a is common to all objects of a class.
- As we can see that value of static variable is common to all objects and it is not reinitialized again to "0" when accessed again.
2) Static Methods
- The most common example of static method we have seen till now is the main() method.
- Static methods are those methods which are made static by preceding them with static keyword. Static methods access static data only.
- Static methods are invoked using class name rather than object name.
- There are some restrictions that are applied to static methods, such as :
- Static methods always access static data. They can’t access non-static data.
- This keyword cannot be used with static method.
- Super keyword cannot be used with static method.
- Let us take an example of static method.
3) Static Block
- Static block is used to initialize static variables. Static block is always executed before main block.
- Let us take an example of static block and see if it executes before main block.
- We can see in the output that the static block is executed before main block and the static variable a is assigned value before main() starts executing.