What is an initialization block?

后端 未结 10 1863
青春惊慌失措
青春惊慌失措 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:53

    nice answer by aioobe adding few more points

    public class StaticTest extends parent {
        static {
            System.out.println("inside satic block");
        }
    
        StaticTest() {
            System.out.println("inside constructor of child");
        }
    
        {
            System.out.println("inside initialization block");
        }
    
        public static void main(String[] args) {
            new StaticTest();
            new StaticTest();
            System.out.println("inside main");
        }
    }
    
    class parent {
        static {
            System.out.println("inside parent Static block");
        }
        {
            System.out.println("inside parent initialisation block");
        }
    
        parent() {
            System.out.println("inside parent constructor");
        }
    }
    

    this gives

    inside parent Static block
    inside satic block
    inside parent initialisation block
    inside parent constructor
    inside initialization block
    inside constructor of child
    inside parent initialisation block
    inside parent constructor
    inside initialization block
    inside constructor of child
    inside main
    

    its like stating the obvious but seems a little more clear.

提交回复
热议问题