Static Initialization Blocks

前端 未结 14 1281
暗喜
暗喜 2020-11-22 01:56

As far as I understood the \"static initialization block\" is used to set values of static field if it cannot be done in one line.

But I do not understand why we ne

14条回答
  •  别那么骄傲
    2020-11-22 02:41

    So you have a static field (it's also called "class variable" because it belongs to the class rather than to an instance of the class; in other words it's associated with the class rather than with any object) and you want to initialize it. So if you do NOT want to create an instance of this class and you want to manipulate this static field, you can do it in three ways:

    1- Just initialize it when you declare the variable:

    static int x = 3;
    

    2- Have a static initializing block:

    static int x;
    
    static {
     x=3;
    }
    

    3- Have a class method (static method) that accesses the class variable and initializes it: this is the alternative to the above static block; you can write a private static method:

    public static int x=initializeX();
    
    private static int initializeX(){
     return 3;
    }
    

    Now why would you use static initializing block instead of static methods?

    It's really up to what you need in your program. But you have to know that static initializing block is called once and the only advantage of the class method is that they can be reused later if you need to reinitialize the class variable.

    let's say you have a complex array in your program. You initialize it (using for loop for example) and then the values in this array will change throughout the program but then at some point you want to reinitialize it (go back to the initial value). In this case you can call the private static method. In case you do not need in your program to reinitialize the values, you can just use the static block and no need for a static method since you're not gonna use it later in the program.

    Note: the static blocks are called in the order they appear in the code.

    Example 1:

    class A{
     public static int a =f();
    
    // this is a static method
     private static int f(){
      return 3;
     }
    
    // this is a static block
     static {
      a=5;
     }
    
     public static void main(String args[]) {
    // As I mentioned, you do not need to create an instance of the class to use the class variable
      System.out.print(A.a); // this will print 5
     }
    
    }
    

    Example 2:

    class A{
     static {
      a=5;
     }
     public static int a =f();
    
     private static int f(){
      return 3;
     }
    
     public static void main(String args[]) {
      System.out.print(A.a); // this will print 3
     }
    
    }
    

提交回复
热议问题