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