What is an initialization block?

后端 未结 10 1883
青春惊慌失措
青春惊慌失措 2020-11-22 03:42

We can put code in a constructor or a method or an initialization block. What is the use of initialization block? Is it necessary that every java program must have it?

10条回答
  •  遥遥无期
    2020-11-22 03:51

    public class StaticInitializationBlock {
    
        static int staticVariable;
        int instanceVariable;
    
        // Static Initialization Block
        static { 
            System.out.println("Static block");
            staticVariable = 5;
    
        }
    
        // Instance Initialization Block
        { 
    
            instanceVariable = 7;
            System.out.println("Instance Block");
            System.out.println(staticVariable);
            System.out.println(instanceVariable);
    
            staticVariable = 10;
        }
    
    
        public StaticInitializationBlock() { 
    
            System.out.println("Constructor");
        }
    
        public static void main(String[] args) {
            new StaticInitializationBlock();
            new StaticInitializationBlock();
        }
    
    }
    

    Output:

    Static block
    Instance Block
    5
    7
    Constructor
    Instance Block
    10
    7
    Constructor
    

提交回复
热议问题