52
Chapter 5 Methods 1

Chapter 5 Methods 1. Motivations Method : groups statements that perform a function. Level of abstraction (black box) Code Reuse – no need to reinvent

Embed Size (px)

DESCRIPTION

Defining Methods 3 A method is a collection of statements that are grouped together to perform an operation.

Citation preview

Page 1: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Chapter 5 Methods

1

Page 2: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

MotivationsMethod :groups statements that perform a function.

Level of abstraction (black box) Code Reuse – no need to reinvent the wheel!

2

Page 3: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 4: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 5: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 6: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 7: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 8: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 9: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 10: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 11: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 12: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 13: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 14: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 15: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 16: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 17: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 18: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 19: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 20: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 21: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 22: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 23: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 24: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 25: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 26: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 27: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 28: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 29: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 30: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 31: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 32: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 33: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Ambiguous Invocation Two or more possible matches for an invocation of a method Compiler cannot determine the most specific match. Compilation error.

33

Page 34: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 35: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 36: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 37: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 38: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 39: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 40: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 41: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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

Page 42: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Benefits of Methods42

• Write a method once and reuse it anywhere.

• Information hiding. Hide the implementation from the user.

• Reduce complexity.

Page 43: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Stepwise RefinementMethod abstraction in program development:“Divide and conquer”

ORStepwise refinement

Decompose program into subproblems.

Subproblems can be further decomposed.

43

Page 44: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

PrintCalender Case Study Let us use the PrintCalendar example to demonstrate the stepwise refinement approach.

44

PrintCalendar Run

Page 45: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Design Diagram45

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 46: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Design Diagram46

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 47: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Design Diagram47

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 48: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Design Diagram48

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 49: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Design Diagram49

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 50: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

Design Diagram50

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 51: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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:

Page 52: Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent

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