Why can't I do assignment outside a method?

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

    A more general answer would be that the class body is about declarations, not statements. There is special provision for statements occuring in class body, but they have to be marked explicitly as either class initializers or instance initializers.

提交回复
热议问题