简体   繁体   中英

Why can't i use static variable in java constructor?

The compiler says illegal modifier for parameter i .
Please tell me what I'm doing wrong. Why can't I use a static variable in a Java constructor?

class Student5{  

    Student5() {  
        static int i = 0;
        System.out.println(i++);  
    }

    public static void main(String args[]){  
        Student5 c1 = new Student5();
        Student5 c2 = new Student5();
        Student5 c3 = new Student5();
    }
}  

Because of where you are declaring i :

Student5(){  
    static int i=0;
    System.out.println(i++);  
}

the compiler treats it as a local variable in the constructor: Local variables cannot be declared as static . For details on what modifiers are allowed for local variables, see Section 14.4 of the Java Language Specification .

Judging from what the code appears to be trying to do, you probably want i to be a static member of Student5 , not a local variable in the constructor:

class Student5{
    private static int i = 0;

    Student5(){  
        System.out.println(i++);  
    }

. . .
}  

If you want to declare static variable then declare it outside of the constructor, at class level like this -

public class Student5{

   private static int i;

}  

You declaration of static occurred at your constructor which is a local variable and local variable can not be static . And that's why you are getting - illegal modifier for parameter i . And finally for initializing static variable you may use a static initialization block (though it's not mandatory) -

public class Student5{

   private static int i;

   static {
      i = 5;
   }

}  

This is how the language was designed.. What if you wanted to have another int field named i in the constructor?, then which i should be considered?. Also, static fields are initialized before the constructor is called ie, during class initilization phase. A constructor gets called only when a new instance is created.

Imagine what would happen (supposed to happen) if you load and initialize a class but not create a new instance .

Static variables are variables that can be referenced without having an instance of the class. By defining one instead of a constructor, which is called when you create an instance of the class, you are contradicting yourself. Either make it defined without having an instance (outside of the constructor and static) or make it specific to an instance (inside the constructor and not static).

You might want to rethink what you are actually trying to do and if you really need a static variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM