Docsity

Creating and Identifying Classes in Java: A Die Example - Prof. Brian C. Tjaden, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
5.1 – Creating Classes
A class can contain da ta declarations and method declarations
int size, weight;
char category;
Data declarations
Method declarations
The values of the data define
the state of an object created from the class
The functionality of the methods define the behaviors of the object
5.1 – Identifying Classes (and Objects)
A class represents a grou p of objects with the same behaviors
Generally, classes that re present objects should be given names tha t are
singular nouns. Examples: Coin, Student, Message
Sometimes it is challengi ng to decide whether something should be
represented as a class
Should an employee's address be represented
as a set of instance variables or as an Address object?
The more you examine th e problem and its details
the more clear these issu es become
When a class becomes t oo complex,
it often should be decom posed into multiple smaller classes
to distribute the responsi bilities
5.1 – Identifying Classes (and Objects)
We want to define classe s with the proper amount of detail
It may be unnecessary to create separate classes for each type of appliance in a house
It may be sufficient to define a m ore general Appliance class with appropriate instance data
It all depends on the details of th e problem being solved
Part of identifying the cla sses we need
is the process of assigning responsibilities to each class
Every activity t hat a program must accomplish
must be represented by one or more methods in one or more classe s
We generally use verbs f or the names of methods
In early stages it is not ne cessary to determine every method of ever y class –
begin with primary respo nsibilities and evolve the design
5.2 – Anatomy of a Class
Consider a six-sided die (singular of dice)
It’s state can be defin ed as which face is showing
It’s primary b ehavior is that it can be rolled
We can represent a die i n Java
by designing a class calle d Die that models this state and behavior
We’ll want to design the D ie class with other data and methods
to make it a versatile and reusable resource
Any given program will n ot necessarily use all aspects of a given clas s
Let’s see how we would use someone’s class of the Die to play snakeyes
die1 5
faceValue
die2 2
faceValue
pf3
pf4

Partial preview of the text

Download Creating and Identifying Classes in Java: A Die Example - Prof. Brian C. Tjaden and more Study notes Data Structures and Algorithms in PDF only on Docsity!

5.1 – Creating Classes

A class can contain data declarations and method declarations

int size, weight;

char category;

Data declarations

Method declarations

The values of the data define

the state of an object created from the class

The functionality of the methods define the behaviors of the object

5.1 – Identifying Classes (and Objects)

A class represents a group of objects with the same behaviors

Generally, classes that represent objects should be given names that are

singular nouns. Examples: Coin, Student, Message

Sometimes it is challenging to decide whether something should be

represented as a class

 Should an employee's address be represented as a set of instance variables or as an Address object?

The more you examine the problem and its details

the more clear these issues become

When a class becomes too complex,

it often should be decomposed into multiple smaller classes

to distribute the responsibilities

5.1 – Identifying Classes (and Objects)

We want to define classes with the proper amount of detail

 It may be unnecessary to create separate classes for each type of appliance in a house  It may be sufficient to define a more general Appliance class with appropriate instance data  It all depends on the details of the problem being solved

Part of identifying the classes we need

is the process of assigning responsibilities to each class

Every activity that a program must accomplish

must be represented by one or more methods in one or more classes

We generally use verbs for the names of methods

In early stages it is not necessary to determine every method of every class –

begin with primary responsibilities and evolve the design

5.2 – Anatomy of a Class

Consider a six-sided die (singular of dice)

 It’s state can be defined as which face is showing

 It’s primary behavior is that it can be rolled

We can represent a die in Java

by designing a class called Die that models this state and behavior

We’ll want to design the Die class with other data and methods

to make it a versatile and reusable resource

Any given program will not necessarily use all aspects of a given class

Let’s see how we would use someone’s class of the Die to play snakeyes

die1 faceValue^5

die2 faceValue^2

5.2 – SnakeEyes.java

// SnakeEyes.java Demonstrates the use of a programmer-defined class. //******************************************************************** public class SnakeEyes { //----------------------------------------------------------------- // Creates two Die objects and rolls them several times, counting // the number of snake eyes that occur. //----------------------------------------------------------------- public static void main (String[] args) { final int ROLLS = 500; int num1, num2, count = 0; Die die1 = new Die(); Die die2 = new Die(); for (int roll=1; roll <= ROLLS; roll++) { num1 = die1.roll(); num2 = die2.roll(); if (num1 == 1 && num2 == 1) // check for snake eyes count++; } System.out.println ("Number of rolls: " + ROLLS); System.out.println ("Number of snake eyes: " + count); System.out.println ("Ratio: " + (float)count / ROLLS); } }

5.2 – Die.java

// Die.java Java Foundations // Represents one die (singular of dice) with faces showing values // between 1 and 6. //******************************************************************** public class Die { private final int MAX = 6; // maximum face value private int faceValue; // current value showing on the die // Constructor: Sets the initial face value of this die. //----------------------------------------------------------------- public Die() { faceValue = 1; } // Computes a new face value for this die and returns the result. //----------------------------------------------------------------- public int roll() { faceValue = (int)(Math.random() * MAX) + 1; return faceValue; } (more…)

5.2 – Die.java

// Face value mutator. The face value is not modified if the // specified value is not valid. //----------------------------------------------------------------- public void setFaceValue (int value) { if (value > 0 && value <= MAX) faceValue = value; } //----------------------------------------------------------------- // Face value accessor. //----------------------------------------------------------------- public int getFaceValue() { return faceValue; } //----------------------------------------------------------------- // Returns a string representation of this die. //----------------------------------------------------------------- public String toString() { String result = Integer.toString(faceValue); return result; } }

5.2 – UML Class Diagrams

A UML class diagram for the SnakeEyes program:

5.3 – Program 2 using Coin

// FlipRace.java Java Foundations public class FlipRace { // Flips two coins until one of them comes up heads three times in a row. public static void main (String[] args) { final int GOAL = 3; int count1 = 0, count2 = 0; Coin coin1 = new Coin(), coin2 = new Coin(); while (count1 < GOAL && count2 < GOAL) { coin1.flip(); coin2.flip(); System.out.println ("Coin 1: " + coin1 + "\tCoin 2: " + coin2); // Increment or reset the counters count1 = (coin1.isHeads())? count1+1 : 0; count2 = (coin2.isHeads())? count2+1 : 0; } if (count1 < GOAL) System.out.println ("Coin 2 Wins!"); else if (count2 < GOAL) System.out.println ("Coin 1 Wins!"); else System.out.println ("It's a TIE!"); } }

5.3 – Mutator Restrictions

Private data are controlled via accessors (“getters”) and mutators (“setters”)

The use of mutators gives the class designer

the ability to restrict a client’s options to modify an object’s state

A mutator is often designed so that the values of variables can be set only within

particular limits

For example, the setFaceValue mutator of the Die class should have restricted

the value to the valid range (1 to MAX)

Such restrictions can be implemented through the use of an if statement in the

body of the constructor.

doIt helpMe

obj.doIt();^ helpMe();

main

5.4 – Method Control Flow

If the called method is in the same class, only the method name is needed

The called method is often part of another class or object

Understanding the control flow is essential to debug!

5.4 – Driver Programs

A driver program drives the use of other, more interesting parts

of a program

A TestCoin class could contain a main method

that drives the use of the Coin class,

exercising its methods

I personally prefer to have the driver inside the class definition

as the class’ main() method.

That way the testing becomes part of the development.

In any case, you should be able to write the driver/main()

before writing the class itself!