Java - Static Keyword
Static
In this note, you will quickly know about the static modifier on variables, constants and methods.
Static Variables
- Static variables are shared by all the instances of the class.
- refer to the common property of all objects (which is not unique for each object)
- Advantages of static variable: makes your program memory efficient (i.e., it saves memory).
Example - The use of Static variable:
1 | //Java Program to illustrate the use of static variable which |
Static Constants
- Static constants are final variables shared by all the instances of the class.
Static Methods
- Static methods are not tied to a specific object.
- You can call the static methods without instantiating an object.
- A static method belongs to the class rather than the object of a class
- A static method can access static data member and can change the value of it.
Example - You can call the static methods without instantiating an object :
1 | //Java Program to get the cube of a given number using the static method |
Restrictions for the static method
- The static method can not use non static data member or call non-static method directly.
this
andsuper
cannot be used in static context.
Why is the Java main method static?
It is because the object is not required to call a static method.
If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.
Static Blocks
- It is executed before the main method at the time of classloading.
- Is used to initialize the static data member.
1 | class A2{ |
Reference
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment