Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes

Similar documents
Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

Programming Lecture 6

COMP 110 Programming Exercise: Simulation of the Game of Craps

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

Chapter 4: Writing Classes

Function Call Stack and Activation Records

Chapter 4 Defining Classes I

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Anatomy of a Class Encapsulation Anatomy of a Method

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

C Functions. 5.2 Program Modules in C

CS 116 Week 8 Page 1

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Functions and Recursion

Lecture 7. Random number generation More randomized data structures Skip lists: ideas and implementation Skip list time costs

CPSC 427: Object-Oriented Programming

EECS168 Exam 3 Review

Lecture 04 FUNCTIONS AND ARRAYS

CS 251 Intermediate Programming Methods and More

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

IT 374 C# and Applications/ IT695 C# Data Structures

CS1004: Intro to CS in Java, Spring 2005

PROGRAMMING LANGUAGE 2

Lecture 5: Methods CS2301


Use the scantron sheet to enter the answer to questions (pages 1-6)

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CO Java SE 8: Fundamentals

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

CS 251 Intermediate Programming Methods and Classes

CSC 1351: Quiz 6: Sort and Search

Introduction to Programming Using Java (98-388)

Creating Java Programs with Greenfoot

Objects and Classes -- Introduction

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

CPSC 427: Object-Oriented Programming

Objects, Subclassing, Subtyping, and Inheritance

CSE123. Program Design and Modular Programming Functions 1-1

Building Java Programs

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

The Notion of a Class and Some Other Key Ideas (contd.) Questions:

CS61B Lecture #32. Last modified: Sun Nov 5 19:32: CS61B: Lecture #32 1

Static Methods. Why use methods?

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

ITI Introduction to Computing II

1 Short Answer (15 Points Each)

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

ECE 122. Engineering Problem Solving with Java

Aggregation. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

ECE 122. Engineering Problem Solving with Java

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

CS 10, Fall 2015, Professor Prasad Jayanti

EECS 1001 and EECS 1030M, lab 01 conflict

ITI Introduction to Computing II

Chapter 1 Getting Started

Chapter 4 Classes in the Java Class Libraries

Basics of Programming with Python

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Chapter 6 Introduction to Defining Classes

9/10/2018 Programming Data Structures Inheritance

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

Programming Exercise 14: Inheritance and Polymorphism

Java Outline (Upto Exam 2)

Programming Assignment #4 Arrays and Pointers

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Software Design and Analysis for Engineers

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

More About Objects and Methods

LAB 13: ARRAYS (ONE DIMINSION)

Chapter 5: Writing Classes and Enums

Chapter 5 Object-Oriented Programming

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

COMP 202 Java in one week

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

CSCE3193: Programming Paradigms

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Class, Variable, Constructor, Object, Method Questions

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

4. Java Project Design, Input Methods

Logistics. Final Exam on Friday at 3pm in CHEM 102

ENCAPSULATION. private, public, scope and visibility rules. packages and package level access.

CSC 310 Programming Languages, Spring 2014, Dr. Dale E. Parson

Breakout YEAH hours. Brahm Capoor & Jared Wolens

Instance Members and Static Members

More about Loops and Decisions

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

CS 139 Practice Midterm Questions #2

CS1150 Principles of Computer Science Methods

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

Transcription:

Student Responsibilities Mat 2170 Week 9 Objects and Classes Spring 2014 Reading: Textbook, Sections 6.1 6.3 Lab 9 Attendance 1 2 Recall: Writing Methods 3 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 Notes About Using Methods 4 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. 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 or 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. 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(); 5 6

RandomGenerator Method Interfaces 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 other classes. To obtain a random value, send a message to the generator (rgen in the last example), which responds with the result. 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 7 8 Using RandomGenerator Methods Notes on Overloading Methods To use RandomGenerator methods, invoke them using the name of your RandomGenerator instance (e.g., rgen) as the receiver. The nextint(), nextdouble(), and nextboolean() methods all exist in more than one form. As an example, you could simulate rolling a die by: int die = rgen.nextint(1, 6); Java determines which version is used by checking the number and types of arguments used. To simulate flipping a coin: boolean isheads = rgen.nextboolean(); Methods that have the same name but differ in their argument structure are said to be overloaded. 9 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()); 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 over. 2. If the total is 7 or 11 (called a natural ), the player wins, game over. 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.) 11 12

Craps Algorithm 13 Roll two dice, yielding total If total is 7 or 11 player automatically wins otherwise if total is 2, 3, or 12 player automatically loses otherwise (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 Simulating Craps rolltwodice() 14 /* 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. 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; 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() 15 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. 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. 17 18

Layered Abstractions Java Packages The RandomGenerator class is actually implemented as a subclass of a class called Random. Every Java class is part of a package, which is a collection of related classes that have been released as a coherent unit. 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. 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. Class hierarchies that define methods at different levels are called layered abstractions. Whenever we refer directly to a class, we should import the package in which it lives. 19 20 Importing Packages Randomness is Difficult 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. Non deterministic behavior turns out to be difficult to achieve on 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. 21 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. 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. Because the process is not truly random, the values generated by RandomGenerator instances are said to be pseudo random Give me the next pseudo random number 155629808 pseudo random number generator instance 23 24

Black Box Operation The Random Number Seed 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. 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 on 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. 25 26 Not so random Numbers Debugging and Random Behavior 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. 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. 27 28 Setting the Seed Chaos Game 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 30

Intervals Two Points on an Interval 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. a DeltaX = (b a)/1 b a+deltax If we use two points, DeltaX is the entire interval. 31 32 Three Points on an Interval Four Points on an Interval DeltaX = (b a)/2 DeltaX=(b a)/3 a a+deltax b a+2deltax a a+deltax a+2deltax b a+3deltax If we use three points, DeltaX is half the entire interval. If we use four points, DeltaX is one third the entire interval. 33 34 Sine & Cosine Curves 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. 35 36

Class Contents Controlling Access to Entries 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 object 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 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. 37 38 Access Privileges public private protected (no keyword) All classes in the program have access; public entries in a class are said to be exported by that class. Access is limited to the class itself, making that entry completely invisible outside the class. Access is restricted to the class that defines these entities, along with any of its subclasses or any classes in the same package. The entry is visible only to classes in the same package, and is called package private. 39