SlinkyMation SlinkyMation - 7 days ago 7
Java Question

Why is this array null when it has already been initialized?

I am confused as to why this array (cumulativeWeights) is said to be null. Here is my (simplified) code:

public class WeightedDieTester
{
public static void main(String[] args)
{
WeightedDie d = new WeightedDie();
}
}





public class Die
{
public Die()
{
this.roll();
}
}





public class WeightedDie extends Die {
double[] cumulativeWeights = {.1, .2, .3, .4, .5, 1};

public WeightedDie() {
}
public int roll() {

for (int i = 0; i < cumulativeWeights.length; i++) { //this is where the nullpointerException is occuring
if (randNum < cumulativeWeights[i]) {
return i + 1;
}
}
return 6;
}
}


So yeah, cumulativeWeights has been initialized and should not be null. Does anyone know why it I am getting that nullpointerexception?

Answer

Inside of the constructor of the super class, the fields of a class are not initialized. You should call roll not from this point. Instances are initialized (and constructors are called) from the farthest super class down to the instance's class.