Why use static blocks over initializing instance variables directly?

前端 未结 5 2039
情歌与酒
情歌与酒 2021-01-04 20:15

Why would I use a static block:

static {
   B = 10;
}

over:

Integer B = 10;

What is the advantages/disadv

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-04 20:49

    First your Integer B appears to be a non static member variable and can not be accessed from a static block. So you either meant to write

    //Initialize static field
    static {
       B = 10;
    }
    static Integer B = 10;
    

    or

    //Initialize member field
    {
       B = 10;
    }
    Integer B = 10;
    

    In both cases you can use it to initialize B with a value that could cause an exception or do something more complex without writing a special method for init.

    {
       try{
          B = thisWillThrowAFileNotFound();
       }catch(FileNotFoundException){
          B = 10;//Set default
       }
    
    }
    

提交回复
热议问题