Java Inheritance: Calling subclass method in super class

时间:2016-12-02 05:20:38

标签: java inheritance

The program has a class relationship in which WeightedDie extends the Die class as follows:

import java.util.Random;

public class Die
{
    private int _maxNumSides;
    private Random _rand;
    // class level variable with visibility for sub classes
    protected int _faceValue;
    public final static int DEFAULT_SIDES = 6;

    // no param constructor for normal 6 sided die
    public Die()
    {
        _rand = new Random();
        _maxNumSides = DEFAULT_SIDES;
        this.roll();
    }

    // will randomly reset the number of dots showing on a side
    public int roll()
    {   
        _faceValue = _rand.nextInt(_maxNumSides) + 1;
        return _faceValue;
    }

    ...

}

and

public class WeightedDie extends Die
{
    private int randomNum;
    private int maxNumSides = 6;
    private double [] weights;
    private Random rand;
    private double sum = 0;
    private double weightRoll;
    private int cumulWeight;
    private double cumulWeightDouble;


public WeightedDie()
{
    super();
}

public WeightedDie(double[] w)
{
   ...
}

public int roll()
{
    cumulWeight = 0;
    cumulWeightDouble = 0;
    weightRoll = 0;
    rand = new Random();

    randomNum = rand.nextInt(100) + 1;

    for(int i = 0; i < 6; i++)
    {
        weightRoll = weights[i]*100;
        cumulWeightDouble = weightRoll + cumulWeightDouble;
        cumulWeight = (int) cumulWeightDouble;

        if(randomNum >= (cumulWeight - weightRoll) && randomNum <= (cumulWeight))
        {
            _faceValue = i;
            break;
        }
    }
    return _faceValue;
}
}

My problem seems to be that the WeightedDie constructor uses the Die constructor with super(). In the Die constructor this.roll() is called, and this is calling WeightedDie's roll() instead of Die's roll(), which gives a null pointer. I want this.roll() in Die to call Die's roll() method. How can this be fixed?

2 个答案:

答案 0 :(得分:-1)

  

在Die构造函数中调用this.roll(),这是调用WeightedDie的roll()而不是Die的roll(),

这是正确但不是问题。

  

给出一个空指针。

显示堆栈跟踪。可能这行有问题:

weightRoll = weights[i]*100;

因为weights数组未初始化。

请参阅:How do I declare and initialize an array in Java?

答案 1 :(得分:-1)

我们有以下选项来解决此问题。

  1. 通过super.roll()方法调用解析空指针异常。
  2. 在超类和子类中更改roll()方法名称
  3. 将超类中的roll()方法更改为private