Student Responsibilities Mat 2170 Week 9 Reading: Textbook, - - PDF document

student responsibilities mat 2170 week 9
SMART_READER_LITE
LIVE PREVIEW

Student Responsibilities Mat 2170 Week 9 Reading: Textbook, - - PDF document

Student Responsibilities Mat 2170 Week 9 Reading: Textbook, Sections 6.1 6.3 Objects and Classes Lab 9 Attendance Spring 2014 1 2 Recall: Writing Methods Notes About Using Methods A method invocation or call uses its name


slide-1
SLIDE 1

Mat 2170 Week 9

Objects and Classes Spring 2014

1

Student Responsibilities

◮ Reading: Textbook, Sections 6.1 – 6.3 ◮ Lab 9 ◮ Attendance

2

Recall: Writing Methods

◮ Decomposition: break a problem down into smaller subproblems ◮ Use methods whenever you can in labs from now on.

scope type name (argument list) { statements in the method body }

  • 1. scope indicates who has access to the method (public)
  • 2. type indicates what type of value the method returns
  • 3. name is the name of the method
  • 4. argument list is the list of declarations for the variables used to

hold the values of each argument

3

Notes About Using Methods

◮ A method invocation or call uses its name and supplies

arguments that correspond to the parameters in the method implementation.

◮ A predicate method returns a boolean value. ◮ You must be aware of the return type of any method you

invoke, since you will either be:

◮ using it in an expression ◮ assigning it to an object ◮ or displaying it

if(!isPalindrome(n))

  • or-

double x = sqrt(y)

◮ Do not place a print or println statement in a method to

display a calculated value unless that is the express purpose of the method. If the return type isn’t void, the method shouldn’t display any results.

4

Chapter Six: Objects and Classes

Before writing our own classes, it helps to look more closely at how to use classes that someone else has developed.

Using the RandomGenerator Class

◮ The RandomGenerator class makes it possible to write

programs that simulate random processes, such as flipping a coin

  • r rolling a die.

◮ Programs that involve random processes like this are said to be

non–deterministic.

◮ Non–determinism is essential to many applications, such as

computer games.

◮ It also has important practical uses in simulations, computer

security, and algorithmic research.

5

Creating a RandomGenerator Object

◮ The first step in writing a program that uses randomness is to

create an instance (object) of the RandomGenerator class.

◮ The best way to do so, is to call the getInstance() method,

which returns a single shared instance of a random generator.

◮ The standard for that declaration looks like this:

private RandomGenerator rgen = RandomGenerator.getInstance();

6

slide-2
SLIDE 2

◮ This declaration usually appears outside of any method (but still

in the program class), and is therefore an example of an instance variable.

◮ The keyword private indicates that this variable can be used

from any method within this class, but is not accessible to

  • ther classes.

◮ To obtain a random value, send a message to the generator

(rgen in the last example), which responds with the result.

7

RandomGenerator Method Interfaces

public int nextInt(int low, int high) Returns a random int in interval [low..high] public int nextInt(int n) Returns a random int in interval [0..n−1] public double nextDouble(double low, double high) Returns a random double d, low≤ d <high public double nextDouble() Returns a random double d, 0 ≤ d < 1 public boolean nextBoolean() Returns a random boolean, which is true 50% of the time public boolean nextBoolean(double p) Returns a random boolean, which is true with probability p, 0 ≤ p < 1 public Color nextColor() Returns a random color

8

Using RandomGenerator Methods

◮ To use RandomGenerator methods, invoke them using the name

  • f your RandomGenerator instance (e.g., rgen) as the receiver.

◮ As an example, you could simulate rolling a die by:

int die = rgen.nextInt(1, 6);

◮ To simulate flipping a coin:

boolean isHeads = rgen.nextBoolean();

9

Notes on Overloading Methods

◮ The nextInt(), nextDouble(), and nextBoolean() methods

all exist in more than one form.

◮ Java determines which version is used by checking the number

and types of arguments used.

◮ Methods that have the same name but differ in their

argument structure are said to be overloaded.

10

Examples: Generating Random Values

◮ To set the variable total to the sum of two six–sided dice:

int d1 = rgen.nextInt(1, 6); int d2 = rgen.nextInt(1, 6); int total = d1 + d2;

◮ To flip a coin that comes up heads 60% of the time:

boolean isHeads = rgen.nextBoolean(0.6);

◮ To randomly change the fill color of rect:

rect.setFillColor(rgen.nextColor());

11

The Dice Game ”Craps”

◮ At the beginning of the game, the player rolls a pair of dice and

computes the total.

  • 1. If the total is 2, 3, or 12 (called ”craps”), the player loses, game
  • ver.
  • 2. If the total is 7 or 11 (called a ”natural”), the player wins, game
  • ver.
  • 3. If the total is any other number (4, 5, 6, 8, 9, or 10), that

number becomes the ”point.” From here, the player keeps rolling the dice until:

3.1 the point comes up again, in which case the player wins or 3.2 a 7 appears, in which case the player loses. (The numbers 2, 3, 11, and 12 have no special significance after the first roll.)

12

slide-3
SLIDE 3

Craps Algorithm

Roll two dice, yielding total If total is 7 or 11 player automatically wins

  • therwise if total is 2, 3, or 12

player automatically loses

  • therwise

(player has rolled 4, 5, 6, 8, 9, or 10, their point) player continues to roll dice until they roll their point and win, or they roll a 7 and lose

13

Simulating Craps – rollTwoDice()

/* Rolls two dice and returns their sum. */ private int rollTwoDice() { int d1 = rgen.nextInt(1, 6); int d2 = rgen.nextInt(1, 6); return d1 + d2; } /* Private instance variables / private RandomGenerator rgen = RandomGenerator.getInstance(); Warning: do not use print() or println() in a method unless that is the method’s purpose.

14

The Craps Program

public void run() { int total = rollTwoDice(); switch (total) { case 7: case 11: println("You rolled a natural. You win."); break; case 2: case 3: case 12: println("You rolled " + total + ". You lose."); break;

15

default: // rolled 4, 5, 6, 8, 9, or 10 int point = total; println("Your point is: " + point + "."); total = rollTwoDice(); while (total != 7 && total != point){ println("You rolled " + total + ", rolling again."); total = rollTwoDice(); } // end while if (total == point) println("You made your point. You win."); else // (total == 7) println("You rolled a 7. You lose."); } // end switch } // end run()

16

Clients and Implementers

◮ It is useful to recognize that there are two perspectives that we

can take with respect to a particular class.

◮ Often, we will find ourselves using a class we didn’t write (for

example, the RandomGenerator class).

◮ When this happens, we are acting as a client of the class. ◮ When we write the code for a method, we are acting as an

implementer.

◮ Clients and Implementers look at a class in different ways.

17

Two Views of Methods

◮ Clients need to know:

◮ what methods are available in a class, and ◮ how to call them

◮ Clients are not interested in the details of how a method works. ◮ The Implementer, on the other hand, is primarily interested in

precisely those details.

◮ The Implementer of a class should try to hide complexity from

its clients.

◮ The RandomGenerator class hides a considerable amount of

complexity.

18

slide-4
SLIDE 4

Layered Abstractions

◮ The RandomGenerator class is actually implemented as a

subclass of a class called Random.

◮ Some of the methods we call to produce random values are

defined in the RandomGenerator class itself; others are inherited from the Random class.

◮ A client does not need to know which is which. ◮ Class hierarchies that define methods at different levels are called

layered abstractions.

19

Java Packages

◮ Every Java class is part of a package, which is a collection of

related classes that have been released as a coherent unit.

◮ The RandomGenerator class is defined in a package called

acm.util, which is part of the ACM Java Libraries.

◮ The Random class is part of the java.util package, which is a

collection of general utility classes.

◮ Whenever we refer directly to a class, we should import the

package in which it lives.

20

Importing Packages

◮ For example, any program using the RandomGenerator class

should include the line: import acm.util.*;

◮ When we use the RandomGenerator class, we do not need to

import the java.util package (unless it is used for some other purpose), since that is taken care of in acm.util.

◮ The fact that RandomGenerator is built on top of Random is

part of the complexity hidden from clients.

21

Randomness is Difficult

◮ Non–deterministic behavior turns out to be difficult to achieve

  • n a computer.

◮ A computer executes its instructions in a precise, predictable way. ◮ If you give a computer program the same inputs, it will generate

the same outputs every time.

◮ This is not what we want in a non–deterministic program.

22

Simulating Randomness

◮ Given that true non–determinism is so difficult to achieve in a

computer, classes such as RandomGenerator must instead simulate randomness by carrying out a deterministic process that satisfies the following criteria:

  • 1. The values generated by that process should be difficult for

human observers to predict.

  • 2. Those values should appear to be random, in the sense that they

should pass statistical tests for randomness.

◮ Because the process is not truly random, the values generated by

RandomGenerator instances are said to be pseudo–random

23

Pseudo–random Numbers

◮ The RandomGenerator class uses a mathematical process to

generate a series of integers that appear to be random.

◮ The code that implements this process is called a

pseudo–random number generator.

◮ The best way to visualize a pseudo–random number generator is

to think of it as a black box that generates a sequence of values, even though the details of how it does so are hidden.

155629808

Give me the next pseudo−random number

generator instance pseudo−random number

24

slide-5
SLIDE 5

Black Box Operation

◮ To obtain the next pseudo–random number, we send a message

to the generator asking for the next number in its sequence.

◮ The generator then responds by returning that value. ◮ Repeating these steps generates a new value each time.

25

The Random Number Seed

◮ The pseudo–random number generator used by the Random and

RandomGenerator classes generates seemingly random values by applying a function to the previous result.

◮ The seed is the starting point for this sequence of values. ◮ As part of the process of starting a program, Java initializes the

seed for its pseudo–random number generator to a value based

  • n the system clock, which changes very quickly on a human

time scale.

◮ Programs executed just a few milliseconds apart will therefore

get a different sequence of random values.

26

Not–so–random Numbers

◮ Computers, however, run much faster than the internal clock can

register.

◮ If we create two RandomGenerator instances in a single

program, it is likely that both will be initialized to the same seed, and therefore, generate exactly the same sequence of values.

◮ This fact explains why it is important to create only one

RandomGenerator instance (like rgen) in an application.

27

Debugging and Random Behavior

◮ Even though unpredictable behavior is essential for programs like

computer games, such unpredictability often makes debugging extremely difficult.

◮ Because the program runs in a different way each time, there is

no way to ensure that a bug that turns up the first time we run a program will happen again the second time around.

◮ To get around this problem, it is often useful to have our

programs run deterministically during the debugging phase.

28

Setting the Seed

◮ To accomplish this, we can use the setSeed() method:

rgen.setSeed(1);

◮ This call sets the random number seed so that the internal

random number sequence will begin at the same point every time the program is executed.

◮ The value 1 is arbitrary — changing this value will change the

sequence, but whatever that sequence is, it will be the same on each run.

29

Chaos Game

30

slide-6
SLIDE 6

Intervals

Suppose we wish to work our way from one end of an interval to the other end, using equal steps. . . We will begin with the smallest value in the interval.

31

Two Points on an Interval (b−a)/1 DeltaX = b a a+DeltaX

If we use two points, DeltaX is the entire interval.

32

Three Points on an Interval b a

a+DeltaX a+2DeltaX DeltaX = (b−a)/2 If we use three points, DeltaX is half the entire interval .

33

Four Points on an Interval b a

a+3DeltaX a+2DeltaX a+DeltaX DeltaX=(b−a)/3

If we use four points, DeltaX is one–third the entire interval.

34

Sine & Cosine Curves

35

Defining Our Own Classes

◮ The standard form of a class definition in Java:

public class name extends superclass { class body }

◮ The extends clause on the header line specifies the name of the

superclass, from which this class is derived.

◮ If the extends clause is missing, the new class becomes a direct

subclass of Object, which is the root of Java’s class hierarchy.

36

slide-7
SLIDE 7

Class Contents

◮ The body of a class consists of a collection of Java definitions

that are generically called entries.

◮ The most common entries are:

  • 1. constructors — how to create an instance (how to initialize an
  • bject of the class)
  • 2. methods — the methods associated with the class
  • 3. instance variables — any necessary local objects
  • 4. named constants — any necessary constants for the class

37

Controlling Access to Entries

◮ Each entry in a Java class is marked with a keyword to control

which classes have access to (can “see”) that entry.

◮ The types of access are termed public, private, and protected. ◮ The text uses only public and private. All entries are marked

as private unless there is a compelling reason to export them.

38

Access Privileges

public All classes in the program have access; public entries in a class are said to be exported by that class. private Access is limited to the class itself, making that entry completely invisible outside the class. protected Access is restricted to the class that defines these entities, along with any of its subclasses or any classes in the same package. (no keyword) The entry is visible only to classes in the same package, and is called package–private.

39