Why can't I do assignment outside a method?

前端 未结 7 1961
不知归路
不知归路 2020-11-22 00:12

If I try to assign a value to a variable in a class, but outside a method I get an error.

class one{
 Integer b;
 b=Integer.valueOf(2);
}

b

7条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 00:35

    you need to do

    class one{
     Integer b;
     {
        b=Integer.valueOf(2);
     }
    }
    

    as statements have to appear in a block of code.

    In this case, the block is an initailiser block which is added to every constructor (or the default constructor in this case) It is run after any call to super() and before the main block of code in any constructor.

    BTW: You can have a static initialiser block with static { } which is called when the class is initialised.

    e.g.

    class one{
     static final Integer b;
    
     static {
        b=Integer.valueOf(2);
     }
    }
    

提交回复
热议问题