Sunday 12 August 2018

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

Example:
class Student{
Student() {
static int i = 0;
System.out.println(i++); 
}
public static void main(String args[]){
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
}

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

Ans:
If you want to declare static variable then declare it outside of the constructor, at class level like this -
public class Student{
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 Student{
private static int i;
static {
i = 5;
}
}

No comments:

Post a Comment