Complete the WeightedDie inheritance free response before reviewing the solution.
Review the WeightedDie
solution with AP CS Tutor Brandon Horn.
WeightedDie
solution
public class WeightedDie extends Die
{
private int favoredSide;
private double weight;
public WeightedDie(int sides, int favoredSide, double weight)
{
super(sides);
this.favoredSide = favoredSide;
this.weight = weight;
}
public int getFavoredSide()
{
return favoredSide;
}
public int roll()
{
if(Math.random() < weight)
return favoredSide;
else
return super.roll();
}
}
Explanation
As with all problems that request an entire class, this problem should be solved using my Class writing order.
A subclass contains things that are new and things that are different.
Method headers
- Subclasses do not inherit constructors, so all constructors are new.
- Method
getFavoredSide
is new (not inDie
). - Method
roll
is different. Methodroll
behaves differently inWeightedDie
than methodroll
inDie
. Methodroll
inWeightedDie
overrides methodroll
inDie
.
Instance variables
Instance variables can only be new. (There is no such thing as an instance variable that is different.) The subclass WeightedDie
stores only the instance variables that are not already stored in Die
.
WeightedDie
must store the favored side and the weight. WeightedDie
does not stores the number of sides, since that is already stored in Die
.
Code inside methods
Constructor
Every subclass constructor must call a superclass constructor, either explicitly or implicitly. In this case, WeightedDie
must explicitly call the Die
constructor because there is no Die
constructor with no parameters. The call must be the first line of the WeightedDie
constructor.
The Die
constructor accepts the number of sides. The WeightedDie
constructor accepts the number of sides as its first parameter. The call super(sides);
passes the number of sides to the Die
constructor.
The WeightedDie
constructor must also set its own instance variables (favoredSide
and weight
) .
getFavoredSide
method
Method getFavoredSide
is a simple accessor method that returns the favored side.
roll
method
Method roll
behaves as described in the problem. A random number is used for probability. See Generate random numbers with Math.random() for additional discussion. If the probability check passes, the favored side is returned.
If the probability check fails, the WeightedDie
is rolled like a Die
. Rolling like a Die
is accomplished by calling the superclass roll
method and returning the result.
Rewriting the code to roll like a Die
is not acceptable. WeightedDie
does not have access to the private
instance variable sides
in Die
. WeightedDie
should not store its own copy of the number of sides. A subclass should not duplicate state (instance variables) or behavior (methods) of its superclass.