Lecture 6: Methods - California State University, Los Angeles
Download
Report
Transcript Lecture 6: Methods - California State University, Los Angeles
Tarik Booker
CS 201
What we will cover…
Methods
Defining a Method
Calling a Method
Void Methods
Passing Arguments by Value
Modularizing Code
Overloading Methods
The Scope of Variables
Method Abstraction and Stepwise
Refinement
Methods
What is a method?
Collection of statements grouped together to
perform an operation
Way of grouping statements to perform some
action
You have already used methods before in
class
Built-in methods
○ System.out.println()
○ Math.pow()
○ Math.sin()
You will now create your own methods
Defining a Method
In order to create our own method, we
define it.
Definition:
modifier returnValueType methodName(list or parameters)
{
// Method body
}
Defining a Method (2)
More detail:
The method max is defined as finding the largest of
two integers
Method definition:
public static int max(int num1, int num2)
{
int result;
if(num1>num2)
result = num1;
else
result = num2;
return result;
}
Defining a Method (3)
Let’s look at that again:
Modifier
Method
Header
Method
Body
Return
Method
value type Name
Formal
parameters
public static int max(int num1, int num2)
{
int result;
Parameter
if(num1>num2)
List
result = num1;
Method
else
Signature
result = num2;
Return
return result;
Value
}
Defining a Method (4)
There are many parts of a method
Method header – specifies all parts of the
method
○ Modifier – statements to differentiate function
(discussed later)
Static – complicated (discussed in Chapter 8)
○ Return Value type – what data type of the
value of the method returns
No return value type? Use void
○ Method name
○ Parameters
Defining a Method (5)
Value-returning method
Method returns a value
Void Method
Method doesn’t return a value
Defining a Method (6)
Parameters
Placeholder for a value given to the method (if it
warrants one)
Formal parameters
Parameter list
○ Method’s type, order, and number of parameters
Parameters are optional
○ A method may contain no parameters
Method signature
Method name + parameter list
Defining a Method (7)
Method body
Collection of statements that implement the
method
Return statement
Required for value-returning methods
Method terminates when a return statement
is executed
Calling a Method
We have covered creating a method
Defining it
Now we want to use the method
We call it
We invoke it
If a method returns a value, we can treat the method like
a value
int larger = max(3,4);
○ We have assigned the result of the method to integer larger
If the method returns void, we must treat it like a
statement
System.out.println(“Welcome to Java”);
Void method
Note: you can treat a value-returning method like a statement, but the
returning value will be ignored.
Calling a Method (2)
When a program calls a method,
program control is transferred to the
called method
Method returns control when return
statement is executed, or ending curly
brace is reached
Look at TestMax.java example
p206
Calling a Method (3)
Each time a method is invoked, the
system creates an activation record
Also called activation frame
Stores parameters and variables for the
method
Places the activation record in a call stack
○ Stored in an area of memory
Look at Figure 6.3
Void Methods
Again, void methods simply are methods
that have no return value
Use void in the return data type
Main is a popular void method
Look 6.4 example
Passing Arguments by Value
Methods can work with parameters
Println prints any string
Max finds maximum of any ints
When calling a method, you need to
provide arguments
Must be given in the same order as their
respective parameters in the method
signature
○ Called parameter order association
Passing Arguments by Value (2)
Look at this function:
public static void nPrintln(String message, int n)
{
for(int i=0; i<n; ++i)
System.out.println(message);
}
This prints the message n number of times
You must invoke it in the proper order, however:
○ nPrintln(“Hi”, 40);
○ nPrintln(3, “Hello”);
Doesn’t work!
Passing Arguments by Value (3)
When you invoke a method with an
argument, the value of the argument is
passed to the parameter
Called pass-by-value
If argument is a variable, the value of the
variable is passed to the method
Let’s look at examples on p213
Modularizing Code
A great way to maintain and reuse code
is to modularize it
Take redundant code and put it into a
method
Instead of using the same code (typing out
the same lines), you can simply call the
method
Look at PrimeNumberMethod.java
○ p216
Modularizing Code (2)
In this example we check for primality
with a method
The method is then called every time we
need it
Primality testing is modularized, or contained
within our method
Overloading Methods
You can different methods with the same
name, as long as their signatures (or
parameters) are different
Called overloading a method
Ex: We used the max method to determine
the maximum value between integers
Now we can make a max method to determine
the maximum value between doubles!
Overloading Methods (2)
Let’s create a max method for doubles!
public static double max(double num1, double num2)
{
if(num1 > num2)
return num1;
else
return num2;
}
This is perfectly legal.
Overloading Methods (3)
Method overloading is a great way to
create methods that do the same thing for
different data types
Great for modularization
Eventually we will use this for classes (202)
Look at this code:
Public static double max(double num1, double
num2, double num3)
{
○ Return max(max(num1, num2), num3);
}
Overloading Methods (4)
Now we have max defined for both integers
and doubles
Max(3, 4)
calls the integer version
Max(3.0, 4.0) calls the double version
What about max(3, 4.0)?
○ What version does this call?
Compiler tries to find best match
○ 3 is converted to 3.0 (widens type) and calls the
double version
○ Max(3.0, 4) also calls the double version
Overloading Methods (5)
Note:
Do not do this:
public static double max(int num1, double num2)
{
//…
}
public static double max(double num1, int num2)
{
//…
}
There is no best match for the method
○ Compiler cannot determine what to use
○ Called an ambiguous invocation
○ Do not do!
Overloading Methods (6)
Important!
You can overload methods by using the
same method name with different parameter
lists
You cannot overload a method by simply
changing the return type!
○ DO NOT DO!
The Scope of Variables
Variable Scope – how accessible a
variable is
Determined from where it is declared
A variable declared in a method is only valid
in that method
○ Variables declared in main are only accessible
(valid) in main
○ Variables declared in a user-defined method
are only accessible in that method
Called local variables
The Scope of Variables (2)
Parameters inside methods are also
considered local variables
Local variables have limited scope
○ Meaning – accessible only in the small are
within their definitions
Variables declared in the initial-action
part of a for loop also have limited scope
Only usable within the for loop
Method Abstraction
A way to more sophisticated
programming involves abstraction
Separating out the implementation from use
Also called encapsulation
○ Information hiding
○ The method implementation is hidden in a
“black box”
Ex: We’ve used System.out.println(), but we
don’t know how it works!
○ It’s okay, so long as it does!
Stepwise Refinement
When writing large programs, we must
break up the program into smaller
pieces
Called stepwise refinement
Decomposes the problem into subproblems
○ Subproblems can also be decomposed
Referred to a “divide and conquer” strategy
○ Smaller program portions – less intimidation
Stepwise Refinement (2)
Approaches
Different ways to approach refinements
Top-down
Starting from the top, break down the
problem and create program stubs
○ Simple, incomplete version of a method
Bottom-up
Implement one method at a time and use
drivers
○ Test program that tests the method
Stepwise Refinement (3)
Which method is best?
Whatever works for you!!!
Benefits of Stepwise Refinement
Makes program simpler to understand
You can reuse methods
Easier to debug, test, and develop
○ You will respect this process later…
Better for facilitating teamwork
○ There’s no escaping teamwork!