Assignment at class level separately from variable declaration

前端 未结 2 1355
[愿得一人]
[愿得一人] 2021-01-29 11:59
class Type {
     int s=10;
     s = 10;

     public static void main(String[]args)
     {

       System.out.println(s);

     }
}

this program creat

2条回答
  •  没有蜡笔的小新
    2021-01-29 12:34

    In Java, the only things that are allowed directly within class bodies are methods, field declarations and blocks, no expression or non-declarative statements. These can only be added within blocks.

    class Type {
        int s;
        { s = 10; }
    }
    

    Putting it in a constructor is probably a better idea though.

    class Type {
        int s;
    
        public Type() { 
            s = 10; 
        }
    }
    

提交回复
热议问题