javaconstructorstaticstatic-variables

Why can't I declare a static variable in a Java constructor?


The compiler says "illegal modifier for parameter i". Please tell me what I'm doing wrong. Why can't I declare 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();
    }
}  

Solution

  • 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++);  
        }
    
    . . .
    }