class level error : expected in java

后端 未结 4 508
陌清茗
陌清茗 2021-01-29 13:36

when I am coding this at class level

int a;
a=5;

it throws error : \"identifier expected\"

But when I declare it as a local variable li

4条回答
  •  面向向阳花
    2021-01-29 14:02

    When you're doing this at class level, you're allowed to combine declaration and assignment in just one statement, like:

    class A {
        int a = 5;
    }
    

    Otherwise, you have to wrap the assignment withing a block (constructor, method, initializer block). For example:

    class A {
        int a;
    
        public A() { a = 5; } //via constructor
    
        void setA() { a = 5; } //via method
    
        { a = 5; } //via initializer block
    }
    

提交回复
热议问题