Assignment at class level separately from variable declaration

前端 未结 2 1325
[愿得一人]
[愿得一人] 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; 
        }
    }
    
    0 讨论(0)
  • 2021-01-29 12:56
    • This restriction by java is so logical. Java is a 100% object oriented language, i.e., we can't do anything without first creating an object. Everything is achieved in java only by playing around with objects. But While building the class, there are certain things that are allowed by Java: 1) Creating constructors 2) Declaring the variables / reference types 3) default variable or reference type initialization

      Eventually the above are allowed so that the same will be used by the various object instances of the class where these are written.

      The actual code which decides what must be done with the above variables are decided by the various methods which consume them.

      Hence the reason why java is very restrictive in nature when it comes to adding any complicated statements at class level. Hope this explanation helps.

    Additionally:

    if you are still intent on adding them, then you are free to use the static block. The java would happily allow all the restricted stuff in there.

    Happy Coding!!

    0 讨论(0)
提交回复
热议问题