Current Android Release version:
Version Code: Pie
Version: 9
API level: 28

Understanding Static keyword in Java

Static keyword can be used with variable, methods, block and 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 (Class methods):
  • 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
Static block:
  • It is used to initialize static data member
           static int a, b;
           static {
                   a = 10;
                   b = 20;
          }
  • static block will be executed before main method at the time of class loading
         class sample {
              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