Chapter 6 Methods 1 Introducing Methods A method



















- Slides: 19
Chapter 6 Methods 1
Introducing Methods A method is a collection of statements that are grouped together to perform an operation. 2
Method Declarations • A method declaration specifies the code that will be executed when the method is invoked (called) • When a method is invoked, the flow of control jumps to the method and executes its code • When complete, the flow returns to the place where the method was called and continues • The invocation may or may not return a value, depending on how the method is defined 3
Method Control Flow • If the called method is in the same class, only the method name is needed compute my. Method(); 4
Method Control Flow • The called method is often part of another class or object main obj. do. It(); do. It help. Me(); 5
The return Statement • The return type of a method indicates the type of value that the method sends back to the calling location • A method that does not return a value has a void return type • A return statement specifies the value that will be returned return expression; • Its expression must conform to the return type 6
animation Calling (invoking) Methods 7
animation Trace Method Invocation i is now 5 8
animation Trace Method Invocation j is now 2 9
animation Trace Method Invocation invoke max(i, j) 10
animation Trace Method Invocation invoke max(i, j) Pass the value of i to num 1 Pass the value of j to num 2 11
animation Trace Method Invocation declare variable result 12
animation Trace Method Invocation (num 1 > num 2) is true since num 1 is 5 and num 2 is 2 13
animation Trace Method Invocation result is now 5 14
animation Trace Method Invocation return result, which is 5 15
animation Trace Method Invocation return max(i, j) and assign the return value to k 16
animation Trace Method Invocation Execute the print statement 17
Overloading Methods public static int max(int num 1, int num 2) { if (num 1 > num 2) return num 1; else return num 2; } public static double max(double num 1, double num 2) { if (num 1 > num 2) return num 1; else return num 2; } 18
Benefits of Methods • Write a method once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity. 19