Java instance variable declare and Initialize in two statements

后端 未结 5 809
天命终不由人
天命终不由人 2020-12-04 03:38

Hi I\'m having problem with initialization in java, following code give me compile error called : expected instanceInt = 100; but already I have declared it. If these thing

5条回答
  •  余生分开走
    2020-12-04 04:22

    According to the Java Language Specification:

    A class body may contain declarations of members of the class, that is, fields (§8.3), classes (§8.5), interfaces (§8.5) and methods (§8.4). A class body may also contain instance initializers (§8.6), static initializers (§8.7), and declarations of constructors (§8.8) for the class.

    However, the statement

    instanceInt = 100;
    

    is none of those things, therefore it is not allowed as part of a class body. What you need to do is this:

    int instanceInt = 100;
    

    This is allowed because it is a field declaration that includes a variable initializer.

提交回复
热议问题