Java

OOP GUIDE / WORK

 

DICE CLASS

 

Topics

  • Implementing methods and a constructor.
  • Using this.

 

 

TASK – DICE CLASS

 

Consider the incomplete Dice class below and do the work below.

 


public
class Dice

{

   public int sides;   //number of sides on die

   public int value;   //value of top face of die

  

   public Dice(int sides)

   {

       

   }

  

   public void roll()

   {

       

   }

  

   public String toString()

   {

       

   }

}

 

WORK

 

  1. Implement the constructor.  Because there is a conflict between the instance variable sides and the local parameter sides, you will have to make use of this.

  2. Implement the roll() method.  It should simply set the instance variable to a new value between 1 and sides inclusively. 

  3. Implement the toString() method.  It should return a String that contains something similar to:

 

     "D6 is showing a 4"

 

  1. In the same class, add a main function.  Yes, in the same class.  Inside main, create a few Dice objects, roll them and display what their result is.

    Note: To minimize confusion, we usually place main in a different class such as DiceTester.  This usually helps students separate the implementation from the using of the class.

    However, because main is a static function, it doesn’t affect the objects that get created by the Dice class.  So really, we can place it inside the Dice class and it doesn’t affect anything.