Anatomy of a Class—Dice
Class
(hover to flip)
Class
Creates a new data type (class)
It is a blueprint for creating objects. Class name, filename, & constructor names are the same.
Private Instance Variables
Private Instance Variables
Store the state of instances (objects) of the class
“State” refers collectively to attributes or properties of objects of this class.
Constructor
Constructor
The constructor initializes the private instance variables.
The constructor is called when an object is instantiated. It has the same name as the class and does not have a return type. It cannot be called directly. It is not a method.
Accessor Methods
Accessor Methods
Accessor methods code the behaviors of the object.
Accessor methods do not change the state (PIVs) of the object.
Mutator Methods
Mutator Methods
Mutator methods code the behaviors of the object.
Mutator methods CAN change the state (PIVs) of the object.
toString()
Method
toString()
Method
Returns information about the object as a String.
The toString()
method inherited from Object should be overridden to create and return a
String that provides useful information about the object.
public class Dice {private int numSides; private int faceValue;public Dice() { numSides = 6; faceValue = 1; } public Dice(int sides) { numSides = sides; faceValue = 1; }public int getNumSides() { return numSides; } public int getFaceValue() { return faceValue; }public int roll() { faceValue = (int)(Math.random() * numSides) + 1; return faceValue; }public String toString() { return "" + faceValue; } }