One of the most important topic that we encounter in java.
We can use static with class name, methods name, variables name and block.
Static keyword mainly used for memory management.
- Static variable
Static variable takes memory only once when the class is loading.
We use static variable to represent common behavior of all objects.
Sometimes in a class we need some variable that would be same all the time, and then should declare
them as static.
Advantage is we can save memory.
Example:
class Employee {
int empId;
String empName;
static String companyName = ABC
}
In a situation, when we know the company name will be same for all employees them it should be static.
- Static method
Static is related to the class not related to object means we dont need to create the object of a class.
Static method use static variables and can modify the value of it.
But the limitation is we cant use non static variables and cannot invoke non static method directly.
We cannot use super and this as a context.
- Static block
Static block is used when we want to execute something before the main method to execute.
Example:
Class StaticBlockExample{
static{
System.out.println(I am static .);
}
Public static void main(String args[]){
StaticBlockExample sBE = new StaticBlockExample();
System.out.println(I am Main);
}
}
I am static will be printed first.
- Static Class
Static class concept use in nested class. Nested class can be static.
Means when we want to access inner class without creating object of outer class.
A Class can be made static only if it is a nested Class.
The nested static class can be accessed without
having an object of outer class.
0 Comment(s)