Savitch Methods - NYU Computer Science Department

Download Report

Transcript Savitch Methods - NYU Computer Science Department

Chapters 4 and 5: Excerpts
Classes, Objects, and Methods




Chapter 4
Class and Method Definitions
Information Hiding and Encapsulation
Objects and Reference
Parameter passing
Java: an Introduction to Computer Science & Programming - Walter Savitch
1
Using Methods


Methods are actions that an object can perform.
To use a method you invoke or call it.
Example of a method call:
speciesOfTheMonth.writeOutput()
calling object—
tells which object
will do the action

Chapter 4
method name—tells
which action the
object will perform
parameter list in
parentheses—parameters
give info to the method, but
in this example there are
no parameters
Two basic kinds of methods:
» methods that return a single value
» void methods that do some action other than returning a
value
Java: an Introduction to Computer Science & Programming - Walter Savitch
2
Return Type of Methods



Chapter 4
All methods require that the return type be specified
Return types may be:
» a primitive data type, such as char, int, double, etc.
» a class, such as String, SpeciesFirstTry, etc.
» void if no value is returned
You can use a method anyplace where it is legal to use its return
type, for example the readLineInt() method of SavitchIn
returns an integer, so this is legal:
int next = SavitchIn.readLineInt();
Java: an Introduction to Computer Science & Programming - Walter Savitch
3
void Method Example
The definition of the writeOutput method of SpeciesFirstTry:

public void writeOutput()
{
System.out.println("Name = " + name);
System.out.println("Population = " + population);
System.out.println("Growth = " + growthRate + "%");
}

Chapter 4
Assuming instance variables name, population, and growthRate
have been defined and assigned values, this method performs an
action (writes values to the screen) but does not return a value
Java: an Introduction to Computer Science & Programming - Walter Savitch
4
Return Statement
Chapter 4

Methods that return a value must execute a return statement
that includes the value to return

For example:
public int getCount()
{
return count;
}
public int count = 0;
Java: an Introduction to Computer Science & Programming - Walter Savitch
5
Method and Class Naming
Conventions
Good Programming Practice
 Use verbs to name void methods
» they perform an action
 Use nouns to name methods that return a value
» they create (return) a piece of data, a thing
 Start class names with a capital letter
 Start method names with a lower case letter
Chapter 4
Java: an Introduction to Computer Science & Programming - Walter Savitch
6
The main Method

A program written to solve a problem (rather than define an
object) is written as a class with one method, main
Invoking the class name invokes the main method
See the text: SpeciesFirstTryDemo

Note the basic structure:


public class SpeciesFirstTryDemo
{
public static void main(String[] args)
{
<statements that define the main method>
}
}
Chapter 4
Java: an Introduction to Computer Science & Programming - Walter Savitch
7
Local Variables and Blocks


Chapter 4
A block (a compound statement) is the set of
statements between a pair of matching braces (curly
brackets)
A variable declared inside a block is known only
inside that block
» it is local to the block, therefor it is called a local
variable
» when the block finishes executing, local variables
disappear
» references to it outside the block cause a compile
error
Java: an Introduction to Computer Science & Programming - Walter Savitch
8
Local Variables and Blocks


Chapter 4
Some programming languages (e.g. C and C++)
allow the variable name to be reused outside the
local block
» it is confusing and not recommended,
nevertheless, it is allowed
However, a variable name in Java can be declared
only once for a method
» although the variable does not exist outside the
block, other blocks in the same method cannot
reuse the variable's name
Java: an Introduction to Computer Science & Programming - Walter Savitch
9
When and Where to Declare
Variables

Declaring variables outside all blocks but within the method
definition makes them available within all the blocks
Good programming Practice:
 declare variables just before you use them
 initialize variables when you declare them
 do not declare variables inside loops
» it takes time during execution to create and destroy
variables, so it is better to do it just once for loops)
 it is ok to declare loop counters in the Initialization field of
for loops, e.g.
for(int i=0; i <10; i++)…
» the Initialization field executes only once, when the
for loop is first entered
Chapter 4
Java: an Introduction to Computer Science & Programming - Walter Savitch
10
Passing Values to a Method: Parameters




Chapter 4
Some methods can be more flexible (therefor useful) if we pass
them input values
Input values for methods are called passed values or
parameters
Parameters and their data types must be specified inside the
parentheses of the heading in the method definition
» these are called formal parameters
The calling object must put values of the same data type, in the
same order, inside the parentheses of the method invocation
» these are called arguments, or actual parameters
Java: an Introduction to Computer Science & Programming - Walter Savitch
11
Parameter Passing Example
//Definition of method to double an integer
public int doubleValue(int numberIn)
{
return 2 * numberIn;
}
//Invocation of the method... somewhere in main...
...
int next = SavitchIn.readLineInt();
System.out.println("Twice next = " +
doubleValue(next));

What is the formal parameter in the method definition?
» numberIn

What is the argument in the method invocation?
» next
Chapter 4
Java: an Introduction to Computer Science & Programming - Walter Savitch
12
Pass-By-Value:
Primitive Data Types as Parameters






Chapter 4
When the method is called, the value of each argument is
copied (assigned) to its corresponding formal parameter
The number of arguments must be the same as the number of
formal parameters
The data types of the arguments must be the same as the
formal parameters and in the same order
Formal parameters are initialized to the values passed
Formal parameters are local to their method
Variables used as arguments cannot be changed by the method
» the method only gets a copy of the variable's value
Java: an Introduction to Computer Science & Programming - Walter Savitch
13
The Math Class
Includes constants Math.PI (approximately 3.14159) and Math.E
(base of natural logarithms which is approximately 2.72)
 Includes three similar static methods: round, floor, and ceil
» All three return whole numbers (although they are type double)
» Math.round returns the whole number nearest its argument
Math.round(3.3) returns 3.0 and Math.round(3.7) returns 4.0
» Math.floor returns the nearest whole number that is equal to or
less than its argument
Math.floor(3.3) returns 3.0 and Math.floor(3.7) returns 3.0
» Math.ceil (short for ceiling) returns the nearest whole number
that is equal to or greater than its argument
Math.ceil(3.3) returns 4.0 and Math.ceil(3.7) returns 4.0

Chapter 4
Java: an Introduction to Computer Science & Programming - Walter Savitch
14
Designing Methods:
Top-Down Design






Chapter 4
In pseudocode, write a list of subtasks that the method must do.
If you can easily write Java statements for a subtask, you are
finished with that subtask.
If you cannot easily write Java statements for a subtask, treat it
as a new problem and break it up into a list of subtasks.
Eventually, all of the subtasks will be small enough to easily
design and code.
Solutions to subtasks might be implemented as private helper
methods.
Top-down design is also known as divide-and-conquer or
stepwise refinement.
Java: an Introduction to Computer Science & Programming - Walter Savitch
15
Programming Tips for
Writing Methods

Apply the principle of encapsulation and detail hiding by using the
public and private modifiers judiciously
» If the user will need the method, make it part of the interface
by declaring it public
» If the method is used only within the class definition (a helper
method, then declare it private

Chapter 4
Create a main method with diagnostic (test) code within a class's
definition
» run just the class to execute the diagnostic program
» when the class is used by another program the class's main
is ignored
Java: an Introduction to Computer Science & Programming - Walter Savitch
16
Testing a Method





Chapter 4
Test programs are sometimes called driver programs
Keep it simple: test only one new method at a time
» driver program should have only one untested method
If method A uses method B, there are two approaches:
Bottom up
» test method B fully before testing A
Top down
» test method A and use a stub for method B
» A stub is a method that stands in for the final version and
does little actual work. It usually does something as trivial as
printing a message or returning a fixed value. The idea is to
have it so simple you are nearly certain it will work.
Java: an Introduction to Computer Science & Programming - Walter Savitch
17
Overloading


Chapter 4
The same method name has more than one definition
within the same class
Each definition must have a different signature
» different argument types, a different number of
arguments, or a different ordering of argument types
» The return type is not part of the signature and
cannot be used to distinguish between two methods
with the same name and parameter types
Java: an Introduction to Computer Science & Programming - Walter Savitch
18
Signature




the combination of method name and number and types of
arguments, in order
equals(Species) has a different signature than
equals(String)
» same method name, different argument types
myMethod(1) has a different signature than myMethod(1, 2)
» same method name, different number of arguments
myMethod(10, 1.2) has a different signature than
myMethod(1.2, 10)
» same method name and number of arguments, but different
order of argument types
Chapter 4
Java: an Introduction to Computer Science & Programming - Walter Savitch
19
Overloading and Argument Type

Accidentally using the wrong datatype as an argument can
invoke a different method

For example, see the Pet class in the text
» set(int) sets the pet's age
» set(double) sets the pet's weight
» You want to set the pet's weight to 6 pounds:
– set(6.0) works as you want because the argument is
type double
– set(6) will set the age to 6, not the weight, since the
argument is type int
Chapter 4
Java: an Introduction to Computer Science & Programming - Walter Savitch
20