I have a class and in that class I have this:
//some code
private int[] data = new int[3];
//some code
Then in my constructor:
public Date(){
data[0] = 0;
data[1] = 0;
data[2] = 0;
}
If I do this, everything is OK. Default data values are initialized but if I instead do this:
public Date(){
int[] data = {0,0,0};
}
It says:
Local variable hides a field
Why?
What's the best way to initialize an array inside the constructor?
data
after"//some code"
is having a scope of the entire class. while the variabledata
in the constructor is having a scope inside the constructor. and once the constructor is done, the variable will be destroyed. And also thedata
variable inside constructor hides the variable by same name in the class. This justifies the errorLocal variable hides a field