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

Size: px
Start display at page:

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

Transcription

1 Student Responsibilities Mat 2170 Week 9 Objects and Classes Spring 2014 Reading: Textbook, Sections 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

2 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 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

3 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() 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

4 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 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 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 pseudo random number generator instance 23 24

5 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 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 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

6 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 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 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

7 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 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

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

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness. Spring 2014 Student Responsibilities Reading: Textbook, Sections 6.1 6.3 Attendance Recall: Writing Methods Decomposition: break a problem down into smaller subproblems Use methods whenever you can in

More information

Programming Lecture 6

Programming Lecture 6 Five-Minute Review 1. What is a method? A static method? 2. What is the motivation for having methods? 3. What role do methods serve in expressions? 4. What are the mechanics of method calling? 5. What

More information

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP 110 Programming Exercise: Simulation of the Game of Craps COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,

More information

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

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times } Rolling a Six-Sided Die face = 1 + randomnumbers.nextint( 6 ); The argument 6 called the scaling factor represents the number of unique values that nextint should produce (0 5) This is called scaling

More information

Chapter 4: Writing Classes

Chapter 4: Writing Classes Chapter 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Writing Classes We've been using predefined classes. Now we will learn to write our own

More information

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

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

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 Assignment 3 Methods Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required. Notes:

More information

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

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited Table of Contents Date(s) Title/Topic Page #s 11/6 Chapter 3 Reflection/Corrections 56 Chapter 4: Writing Classes 4.1 Objects Revisited 57 58-59 look over your Ch 3 Tests and write down comments/ reflections/corrections

More information

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

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects Administrative Stuff September 12, 2007 HW3 is due on Friday No new HW will be out this week Next Tuesday we will have Midterm 1: Sep 18 @ 6:30 7:45pm. Location: Curtiss Hall 127 (classroom) On Monday

More information

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

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 4: Writing Classes Objects An object has: Presentation slides for state - descriptive characteristics Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus,

More information

Anatomy of a Class Encapsulation Anatomy of a Method

Anatomy of a Class Encapsulation Anatomy of a Method Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and

More information

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

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

CS 116 Week 8 Page 1

CS 116 Week 8 Page 1 CS 116 Week 8: Outline Reading: 1. Dale, Chapter 11 2. Dale, Lab 11 Objectives: 1. Mid-term exam CS 116 Week 8 Page 1 CS 116 Week 8: Lecture Outline 1. Mid-term Exam CS 116 Week 8 Page 2 CS 116 Week 8:

More information

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

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

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 COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 Objects 3 1 Static member variables So far: Member variables

More information

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 COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 - Week 7 1 Static member variables So far: Member variables

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

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

Lecture 7. Random number generation More randomized data structures Skip lists: ideas and implementation Skip list time costs Lecture 7 Random number generation More randomized data structures Skip lists: ideas and implementation Skip list time costs Reading: Skip Lists: A Probabilistic Alternative to Balanced Trees paper (Pugh);

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 17 March 31, 2016 CPSC 427, Lecture 17 1/29 Name Visibility Demo: Craps Game CPSC 427, Lecture 17 2/29 Name Visibility CPSC 427, Lecture

More information

EECS168 Exam 3 Review

EECS168 Exam 3 Review EECS168 Exam 3 Review Exam 3 Time: 2pm-2:50pm Monday Nov 5 Closed book, closed notes. Calculators or other electronic devices are not permitted or required. If you are unable to attend an exam for any

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

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

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

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

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.5: Methods A Deeper Look Xianrong (Shawn) Zheng Spring 2017 1 Outline static Methods, static Variables, and Class Math Methods with Multiple

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.aspx?m=5507&c=618&mo=18917&t=191&sy=2012&bl...

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.aspx?m=5507&c=618&mo=18917&t=191&sy=2012&bl... Page 1 of 13 Units: - All - Teacher: ProgIIIJavaI, CORE Course: ProgIIIJavaI Year: 2012-13 Intro to Java How is data stored by a computer system? What does a compiler do? What are the advantages of using

More information

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

Use the scantron sheet to enter the answer to questions (pages 1-6) Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object

More information

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

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015 Classwork 7: Craps N. Duong & R. Rodriguez, Java Crash Course January 6, 2015 For this classwork, you will be writing code for the game Craps. For those of you who do not know, Craps is a dice-rolling

More information

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

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004 Type Hierarchy Comp-303 : Programming Techniques Lecture 9 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 9 Comp 303 : Programming Techniques Page 1 Last lecture...

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

CO Java SE 8: Fundamentals

CO Java SE 8: Fundamentals CO-83527 Java SE 8: Fundamentals Summary Duration 5 Days Audience Application Developer, Developer, Project Manager, Systems Administrator, Technical Administrator, Technical Consultant and Web Administrator

More information

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

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created. + Inheritance + Inheritance Classes that we design in Java can be used to model some concept in our program. For example: Pokemon a = new Pokemon(); Pokemon b = new Pokemon() Sometimes we need to create

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CSC 1351: Quiz 6: Sort and Search

CSC 1351: Quiz 6: Sort and Search CSC 1351: Quiz 6: Sort and Search Name: 0.1 You want to implement combat within a role playing game on a computer. Specifically, the game rules for damage inflicted by a hit are: In order to figure out

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Creating Java Programs with Greenfoot

Creating Java Programs with Greenfoot Creating Java Programs with Greenfoot Using Randomization and Understanding Dot Notation and Constructors 1 Copyright 2012, Oracle and/or its affiliates. All rights Overview This lesson covers the following

More information

Objects and Classes -- Introduction

Objects and Classes -- Introduction Objects and Classes -- Introduction Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes

More information

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

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes 1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 18 November 7, 2016 CPSC 427, Lecture 18 1/19 Demo: Craps Game Polymorphic Derivation (continued) Name Visibility CPSC 427, Lecture 18 2/19

More information

Objects, Subclassing, Subtyping, and Inheritance

Objects, Subclassing, Subtyping, and Inheritance Objects, Subclassing, Subtyping, and Inheritance Brigitte Pientka School of Computer Science McGill University Montreal, Canada In these notes we will examine four basic concepts which play an important

More information

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s);

More information

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

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen CSCI 136 Data Structures & Advanced Programming Fall 2018 Instructors Bill Lenhart & Bill Jannen Administrative Details Lab 1 handout is online Prelab (should be completed before lab): Lab 1 design doc

More information

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

The Notion of a Class and Some Other Key Ideas (contd.) Questions: The Notion of a Class and Some Other Key Ideas (contd.) Questions: 1 1. WHO IS BIGGER? MR. BIGGER OR MR. BIGGER S LITTLE BABY? Which is bigger? A class or a class s little baby (meaning its subclass)?

More information

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

CS61B Lecture #32. Last modified: Sun Nov 5 19:32: CS61B: Lecture #32 1 CS61B Lecture #32 Today: Pseudo-random Numbers (Chapter 11) What use are random sequences? What are random sequences? Pseudo-random sequences. How to get one. Relevant Java library classes and methods.

More information

Static Methods. Why use methods?

Static Methods. Why use methods? Static Methods A method is just a collection of code. They are also called functions or procedures. It provides a way to break a larger program up into smaller, reusable chunks. This also has the benefit

More information

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

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Things to Review Review the Class Slides: Key Things to Take Away Do you understand

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

1 Short Answer (15 Points Each)

1 Short Answer (15 Points Each) Name: Write all of your responses on these exam pages. If you need extra space please use the backs of the pages. 1 Short Answer (15 Points Each) 1. Write the following Java declarations, (a) A double

More information

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation Outline Problem: Create, read in and print out four sets of student grades Setting up the problem Breaking

More information

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

Aggregation. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos. Aggregation Thursday, July 6 2006 CSE 1020, Summer 2006, Overview (1): Before We Begin Some administrative details Some questions to consider Aggregation Overview / Introduction The aggregate s constructor

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 5 Anatomy of a Class Outline Problem: How do I build and use a class? Need to understand constructors A few more tools to add to our toolbox Formatting

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

CS 10, Fall 2015, Professor Prasad Jayanti

CS 10, Fall 2015, Professor Prasad Jayanti Problem Solving and Data Structures CS 10, Fall 2015, Professor Prasad Jayanti Midterm Practice Problems We will have a review session on Monday, when I will solve as many of these problems as possible.

More information

EECS 1001 and EECS 1030M, lab 01 conflict

EECS 1001 and EECS 1030M, lab 01 conflict EECS 1001 and EECS 1030M, lab 01 conflict Those students who are taking EECS 1001 and who are enrolled in lab 01 of EECS 1030M should switch to lab 02. If you need my help with switching lab sections,

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Chapter 4 Classes in the Java Class Libraries

Chapter 4 Classes in the Java Class Libraries Programming Fundamental I ACS-1903 Chapter 4 Classes in the Java Class Libraries 1 Random Random The Random class provides a capability to generate pseudorandom values pseudorandom because the stream of

More information

Basics of Programming with Python

Basics of Programming with Python Basics of Programming with Python A gentle guide to writing simple programs Robert Montante 1 Topics Part 3 Obtaining Python Interactive use Variables Programs in files Data types Decision-making Functions

More information

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

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods Encapsulation You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods external - the interaction of the object with other objects in the program

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

9/10/2018 Programming Data Structures Inheritance

9/10/2018 Programming Data Structures Inheritance 9/10/2018 Programming Data Structures Inheritance 1 Email me if the office door is closed 2 Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same

More information

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

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object Unit 8 Inheritance Summary Inheritance Overriding of methods and polymorphism The class Object 8.1 Inheritance Inheritance in object-oriented languages consists in the possibility of defining a class that

More information

Programming Exercise 14: Inheritance and Polymorphism

Programming Exercise 14: Inheritance and Polymorphism Programming Exercise 14: Inheritance and Polymorphism Purpose: Gain experience in extending a base class and overriding some of its methods. Background readings from textbook: Liang, Sections 11.1-11.5.

More information

Java Outline (Upto Exam 2)

Java Outline (Upto Exam 2) Java Outline (Upto Exam 2) Part 4 IF s (Branches) and Loops Chapter 12/13 (The if Statement) Hand in Program Assignment#1 (12 marks): Create a program called Ifs that will do the following: 1. Ask the

More information

Programming Assignment #4 Arrays and Pointers

Programming Assignment #4 Arrays and Pointers CS-2301, System Programming for Non-majors, B-term 2013 Project 4 (30 points) Assigned: Tuesday, November 19, 2013 Due: Tuesday, November 26, Noon Abstract Programming Assignment #4 Arrays and Pointers

More information

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

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University 9/5/6 CS Introduction to Computing II Wayne Snyder Department Boston University Today: Arrays (D and D) Methods Program structure Fields vs local variables Next time: Program structure continued: Classes

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

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.

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. Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

More information

More About Objects and Methods

More About Objects and Methods More About Objects and Methods Chapter 6 Objectives Define and use constructors Write and use static variables and methods Use methods from class Math Use predefined wrapper classes Use stubs, drivers

More information

LAB 13: ARRAYS (ONE DIMINSION)

LAB 13: ARRAYS (ONE DIMINSION) Statement Purpose: The purpose of this Lab. is to practically familiarize student with the concept of array and related operations performed on array. Activity Outcomes: As a second Lab on Chapter 7, this

More information

Chapter 5: Writing Classes and Enums

Chapter 5: Writing Classes and Enums Chapter 5: Writing Classes and Enums CS 121 Department of Computer Science College of Engineering Boise State University August 22, 2016 Chapter 5: Writing Classes and Enums CS 121 1 / 48 Chapter 5 Topics

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

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

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill CSCI 136 Data Structures & Advanced Programming Lecture 3 Fall 2017 Instructors: Bill & Bill Administrative Details Lab today in TCL 216 (217a is available, too) Lab is due by 11pm Sunday Copy your folder

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

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

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects CmSc 150 Fundamentals of Computing I Lesson 28: Introduction to Classes and Objects in Java 1. Classes and Objects True object-oriented programming is based on defining classes that represent objects with

More information

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

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course : Advanced Java Concepts + Additional Questions from Earlier Parts of the Course 1. Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... In what order

More information

CSCE3193: Programming Paradigms

CSCE3193: Programming Paradigms CSCE3193: Programming Paradigms Nilanjan Banerjee University of Arkansas Fayetteville, AR nilanb@uark.edu http://www.csce.uark.edu/~nilanb/3193/s10/ Programming Paradigms 1 Java Packages Application programmer

More information

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

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

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

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

4. Java Project Design, Input Methods

4. Java Project Design, Input Methods 4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java

More information

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

Logistics. Final Exam on Friday at 3pm in CHEM 102 Java Review Logistics Final Exam on Friday at 3pm in CHEM 102 What is a class? A class is primarily a description of objects, or instances, of that class A class contains one or more constructors to create

More information

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

ENCAPSULATION. private, public, scope and visibility rules. packages and package level access. ENCAPSULATION private, public, scope and visibility rules. packages and package level access. Q. Explain the term Encapsulation with an example? Ans: The wrapping up to data and methods into a single units

More information

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

CSC 310 Programming Languages, Spring 2014, Dr. Dale E. Parson CSC 310 Programming Languages, Spring 2014, Dr. Dale E. Parson Assignment 3, Perquacky in Python, due 11:59 PM, Saturday April 12, 2014 I will turn the solution back on Monday April 14, after which I will

More information

Breakout YEAH hours. Brahm Capoor & Jared Wolens

Breakout YEAH hours. Brahm Capoor & Jared Wolens Breakout YEAH hours Brahm Capoor & Jared Wolens Road Map YEAH hour schedule Deadline: Due Wednesday, February 8th Lecture Review Using the debugger Assignment Overview Q&A! YEAH hours this quarter Assignment

More information

Instance Members and Static Members

Instance Members and Static Members Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these

More information

More about Loops and Decisions

More about Loops and Decisions More about Loops and Decisions 5 In this chapter, we continue to explore the topic of repetition structures. We will discuss how loops are used in conjunction with the other control structures sequence

More information

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

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1 Object-Oriented Languages and Object-Oriented Design Ghezzi&Jazayeri: OO Languages 1 What is an OO language? In Ada and Modula 2 one can define objects encapsulate a data structure and relevant operations

More information

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

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an

More information

CS 139 Practice Midterm Questions #2

CS 139 Practice Midterm Questions #2 CS 139 Practice Midterm Questions #2 Spring 2016 Name: 1. Write Java statements to accomplish each of the following. (a) Declares numbers to be an array of int s. (b) Initializes numbers to contain a reference

More information

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles of Computer Science Methods Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Find the sum of integers from 1 to

More information

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

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci) Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci) Sung Hee Park Department of Mathematics and Computer Science Virginia State University September 18, 2012 The Object-Oriented Paradigm

More information