Why can't I do assignment outside a method?

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

    In Java, when defining a class, you can define variables with default values and add methods. Any executable code (such as assignments) MUST be contained in a method.

提交回复
热议问题