Static Initialization Blocks

前端 未结 14 1485
暗喜
暗喜 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条回答
  •  萌比男神i
    2020-11-22 02:40

    static block is used for any technology to initialize static data member in dynamic way,or we can say for the dynamic initialization of static data member static block is being used..Because for non static data member initialization we have constructor but we do not have any place where we can dynamically initialize static data member

    Eg:-class Solution{
             // static int x=10;
               static int x;
           static{
            try{
              x=System.out.println();
              }
             catch(Exception e){}
            }
           }
    
         class Solution1{
          public static void main(String a[]){
          System.out.println(Solution.x);
            }
            }
    

    Now my static int x will initialize dynamically ..Bcoz when compiler will go to Solution.x it will load Solution Class and static block load at class loading time..So we can able to dynamically initialize that static data member..

    }

提交回复
热议问题