Why can't I do assignment outside a method?

前端 未结 7 1966
不知归路
不知归路 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:51

    Because the assignments are statements and statements are allowed only inside blocks of code(methods, constructors, static initializers, etc.)

    Outside of these only declarations are allowed.

    This :

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

    is a declaration with an initializer. That's why is accepted

提交回复
热议问题