Upload
candice-thomas
View
216
Download
0
Embed Size (px)
DESCRIPTION
Defining Methods 3 A method is a collection of statements that are grouped together to perform an operation.
Citation preview
Chapter 5 Methods
1
MotivationsMethod :groups statements that perform a function.
Level of abstraction (black box) Code Reuse – no need to reinvent the wheel!
2
Defining Methods3
A method is a collection of statements that are grouped together to perform an operation.
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Method Signature4
Method signature is the combination of the method name and the parameter list.
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Formal Parameters5
The variables defined in the method header are known as formal parameters.
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Actual Parameters6
When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Return Value Type7
A method may return a value.
If the method does not return a value, the returnValueType is the keyword void. (i.e., main method)
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Calling Methods8
Listing 5.1 Testing the max method
This program demonstrates calling a method max to return the largest of the int values
TestMax Run
Calling Methods, cont.9
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
pass the value of i pass the value of j
animation
Trace Method Invocation10
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
i is now 5
animation
Trace Method Invocation11
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
j is now 2
animation
Trace Method Invocation12
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
invoke max(i, j)
animation
Trace Method Invocation13
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
invoke max(i, j)Pass the value of i to num1Pass the value of j to num2
animation
Trace Method Invocation14
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
declare variable result
animation
Trace Method Invocation15
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
(num1 > num2) is true since num1 is 5 and num2 is 2
animation
Trace Method Invocation16
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
result is now 5
animation
Trace Method Invocation17
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
return result, which is 5
animation
Trace Method Invocation18
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
return max(i, j) and assign the return value to k
animation
Trace Method Invocation19
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Execute the print statement
animation
CAUTIONA return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value.
20
To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated.
public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; }
(a)
Should be
(b)
public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else return –1; }
Call Stacks 21
(a) The main method is invoked.
Space required for the main method k: j: 2 i: 5
(b) The max method is invoked.
Space required for the max method num2: 2 num1: 5
(d) The max method is finished and the return value is sent to k.
(e) The main method is finished.
Stack is empty
Space required for the main method k: j: 2 i: 5
Space required for the main method k: 5 j: 2 i: 5
(c) The max method is being executed.
Space required for the max method result: 5 num2: 2 num1: 5
Space required for the main method k: j: 2 i: 5
Trace Call Stack
The main method is invoked.
i: 5
22
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
i is declared and initialized
animation
Trace Call Stack
The main method is invoked.
j: 2 i: 5
23
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
j is declared and initialized
animation
Trace Call Stack
The main method is invoked.
Space required for the main method k:
j: 2 i: 5
24
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Declare k
animation
Trace Call Stack
The main method is invoked.
Space required for the main method k:
j: 2 i: 5
25
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Invoke max(i, j)
animation
Trace Call Stack
The max method is invoked.
num2: 2 num1: 5
Space required for the main method k:
j: 2 i: 5
26
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
pass the values of i and j to num1 and num2
animation
Trace Call Stack
The max method is invoked.
result:
num2: 2 num1: 5
Space required for the main method k:
j: 2 i: 5
27
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
pass the values of i and j to num1 and num2
animation
Trace Call Stack
The max method is invoked.
result:
num2: 2 num1: 5
Space required for the main method k:
j: 2 i: 5
28
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
(num1 > num2) is true
animation
Trace Call Stack
The max method is invoked.
Space required for the max method result: 5
num2: 2 num1: 5
Space required for the main method k:
j: 2 i: 5
29
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Assign num1 to result
animation
Trace Call Stack
The max method is invoked.
Space required for the max method result: 5
num2: 2 num1: 5
Space required for the main method k:5
j: 2 i: 5
30
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Return result and assign it to k
animation
Trace Call Stack
The main method is invoked.
Space required for the main method k:5
j: 2 i: 5
31
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Execute print statement
animation
Overloading MethodsTwo methods can have the same namebut different argument lists.
Java examines the signatures to determine which method to call.
Unlike C++, operators cannot be overloaded by the user.
32
Ambiguous Invocation Two or more possible matches for an invocation of a method Compiler cannot determine the most specific match. Compilation error.
33
Ambiguous Invocationpublic class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); } public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; }}
34
Scope of Local VariablesLocal variable: defined inside a method.
Scope: part of program where variable can be referenced.
The scope of a local variable: from declaration until end of the block that contains it
35
Scope of Local Variables, cont.
Can you declare a local variable with the same name multiple times in a method?
If the statements are in different non-nesting blocks of code
36
Scope of Local Variables, cont.Variable declared in the initial action part of for loop:
has scope in the entire loop Variable declared inside for loop body:
has scope from its declaration to the end of the block
37
public static void method1() { . . for (int i = 1; i < 10; i++) { . . int j; . . . } }
The scope of j
The scope of i
Scope of Local Variables, cont.
38
public static void method1() { int x = 1; int y = 1;
for (int i = 1; i < 10; i++) {
x += i; }
for (int i = 1; i < 10; i++) {
y += i; } }
It is fine to declare i in two non-nesting blocks public static void method2() {
int i = 1; int sum = 0;
for (int i = 1; i < 10; i++) {
sum += i; } }
It is wrong to declare i in two nesting blocks
Scope of Local Variables, cont.// Fine with no errorspublic static void correctMethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) { x += i; } // i is declared again for (int i = 1; i < 10; i++) { y += i; }}
39
Scope of Local Variables, cont. 40
// With no errorspublic static void incorrectMethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; }}
Method AbstractionYou can think of the method body as a black box that contains the detailed implementation for the method.
41
Method Header
Method body Black Box
Optional arguments for Input
Optional return value
Benefits of Methods42
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation from the user.
• Reduce complexity.
Stepwise RefinementMethod abstraction in program development:“Divide and conquer”
ORStepwise refinement
Decompose program into subproblems.
Subproblems can be further decomposed.
43
PrintCalender Case Study Let us use the PrintCalendar example to demonstrate the stepwise refinement approach.
44
PrintCalendar Run
Design Diagram45
printCalendar (main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
Design Diagram46
printCalendar (main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
Design Diagram47
printCalendar (main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
Design Diagram48
printCalendar (main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
Design Diagram49
printCalendar (main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
Design Diagram50
printCalendar (main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
Implementation: Top-Down51
A Skeleton for printCalendar
Top-down approach:Work your way down the structure chart
Invoke an incomplete method using method stubs.
Implement the main method first and then use a stub for the printMonth method. For example, let printMonth display the year and the month in the stub. Thus, your program may begin like this:
Implementation: Bottom-Up52
Bottom-up approach: Work your way up the structure chart
Write program to test each method implemented.
Stepwise refinement in either direction implements the methods incrementally helps isolate programming errors