Static keyword can be used with variable, methods, block and nested class.
Static variable (Class variables):
static {
a = 10;
b = 20;
}
static {
System.out.println("This will be executed before main");
}
public static void main(String args[]) {
System.out.println("Main method");
}
}
Static nested class:
Static variable (Class variables):
- static variable belongs to the class and can be accessed without creating instance of the class
- static variables are initialized only once at the start of execution. These variables will be initialized first before initialization of any instance variables
- only single copy of static variable is created and shared among all the instances of the class
- static variable gets memory only once in class area at the time of class loading
- static method belongs to the class and can be accessed without creating instance of the class
- static methods can not access non static data member or can not call non static method. It can access only static data
- "this" and "Super" can not be used
- It is used to initialize static data member
static {
a = 10;
b = 20;
}
- static block will be executed before main method at the time of class loading
static {
System.out.println("This will be executed before main");
}
public static void main(String args[]) {
System.out.println("Main method");
}
}
Static nested class:
- Java does not allow you to create top level static class, only nested static classes are allowed
- nested classes that are declared with static are called static nested classes
No comments:
Post a Comment