Java- Static Keyword
The static keyword can be used in 3 scenarios:
- static variables
- static methods
- static blocks of code
1. Static Variable :
Without the “static” keyword, it’s called
instance variable
, and each instance of the class has its own copy of the variable.- It is a variable which belongs to the class and not to object(instance)
- Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
- A single copy to be shared by all instances of the class
- A static variable can be accessed directly by the class name and doesn’t need any object
- Syntax : <class-name>.<variable-name>
2. Static Method:
Any method defined as Static can be called without creating an object of class. The best example is main method , as at the start of execution no object created so main method is defined as Static.Astatic method belongs to class rather than an object of the class
Calling Static Methods
Invoke static methods using the name of the class followed by dot (.), then the name of the method:
classname.staticMethodName(args,...)
There are two main restrictions for the static method. They are: |
|
No comments:
Post a Comment