Download presentation
Presentation is loading. Please wait.
Published byAndra Butler Modified over 9 years ago
1
Methods Chapter 6
2
2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This can be done by putting the code in a method Various objects in a program can invoke the same method
3
3 Program Modules Divide and conquer technique Construct a large program from smaller pieces (or modules) Can be accomplished using methods static methods can be called without the need for an object of the class
4
4 static Methods static method (or class method) Applies to the class as a whole instead of a specific object of the class Call a static method by using the method call: ClassName.methodName( arguments ) All methods of the Math class are static example : Math.sqrt( 900.0 )
5
5 static Methods Method main main is declared static so it can be invoked without creating an object of the class containing main Any class can contain a main method The JVM invokes the main method belonging to the class specified by the first command-line argument to the java command
6
6 Predefined Methods The Math class These methods are called by The name of the class The dot. operator The name of the method Example: double y = Math.cos(x);
7
7 Constants Keyword final Cannot be changed after initialization static fields (or class variables) Are fields where one copy of the variable is shared among all objects of the class Math.PI and Math.E are final static fields of the Math class
8
8 Method Declaration Syntax modifiers returnType methodName (parameterDeclaration) { statements } modifiers : describers (public, private, etc.) returnType : type of value returned by method, or void if it does not return a value methodName : identifier that names the method parameterDeclaration : list of parameters, separated by commas statements : define the behavior of the method
9
9 Method Declaration View declaration of methods in a class for finding maximums, Fig. 6.3Fig. 6.3 Note method for input, call of method maximum Note method for actual determining of maximum View test program, Fig 6.4Fig 6.4 Note declaration of instance of new class Note call of class methods
10
10 Alternative Method Declaration View alternative solutionalternative solution Declare methods in the application Have them follow method main() Although they can be anywhere in the class Note they must be static
11
11 Declaring and Using Methods Three ways to call a method: Use a method name by itself to call another method of the same class Use a variable containing a reference to an object, followed by a dot (. ) and the method name to call a method of the referenced object Use the class name and a dot (. ) to call a static method of a class Note: static methods cannot call non-static methods of the same class directly
12
12 Declaring and Using Methods Three ways to return control to the calling statement: If method does not return a result: Program flow reaches the method-ending right brace or … Program executes the statement return; If method does return a result: Program executes the statement return expression; expression is first evaluated and then its value is returned to the caller
13
13 Argument Promotion Coercion of arguments Forcing arguments to appropriate type to pass to method System.out.println( Math.sqrt( 4 ) ); Evaluates Math.sqrt( 4 ) Then evaluates System.out.println()
14
14 Argument Promotion Promotion rules Specify how to convert types without data loss
15
15 Java API Packages Predefined classes grouped into categories of related classes Called packages Called the Java Application Programming Interface (API) Note the often used API packagesAPI packages
16
16 Random-Number Generation Consider the random method in the Math class Generates a random double 0 <= n < 1.0 The number can be manipulated and cast as an int to get desired range For the roll of a die Uses object of class Randomclass Random Note Figure 6.7 and Figure 6.8Figure 6.7 Figure 6.8
17
17 Game of Chance Rules for "Craps" Roll dice first time If sum equals 7 or 11, the player wins If sum equals 2, 3 or 12, the player loses Any other sum (4, 5, 6, 8, 9, 10) is that player’s point Keep rolling dice until… Sum matches player point Player wins Sum equals 7 Player loses
18
18 Game of Chance Note the adapted version of Figure 6.9Figure 6.9 An application Note Private class variables Public methods The toUpperClass function requires Character. (a non instantiating class)
19
19 Scope of Declarations Scope of a parameter is body of method where declaration appears Scope of local variable is from point of declaration to end of block Scope of label in labeled break/continue is statement enclosed by labeled statement Scope of local-variable in initialization of for( ) is for body of for and rest of header Scope of method or field of class is body of class View Figure 6.11
20
20 Shadowing A field is shadowed (or hidden) if a local variable or parameter has the same name as the field This lasts until the local variable or parameter goes out of scope View example Figure 6.11 Variables with different scopesFigure 6.11 Figure 6.12 Test programFigure 6.12
21
21 Method Overloading Multiple methods with same name can be declared in same class Methods must have different signatures Different numbers, types, order of parameters Example Figure 6.13 Overload example classFigure 6.13 Figure 6.14 Overload test programFigure 6.14
22
22 Recursion Recursive method Calls itself (directly or indirectly) through another method Method knows how to solve only a base case Method divides problem Base case Simpler problem – Method now divides simpler problem until solvable Recursive call Recursive step
23
23 2! = 2 * 1 = 2 is returned (a) Sequence of recursive calls. (b) Values returned from each recursive call. Final value = 120 5! = 5 * 24 = 120 is returned 4! = 4 * 6 = 24 is returned 3! = 3 * 2 = 6 is returned 1 returned 5! 1 4 * 3! 3 * 2! 2 * 1! 5! 1 4 * 3! 3 * 2! 2 * 1! 5 * 4! Recursive Evaluation of 5!
24
24 Recursive Factorial Program Function factorial() in Figure 6.15Figure 6.15 Note Initial call to factorial() Anchor or base case Recursive call
25
25 Recursive Fibonacci Program Consider function from program public long fibonacci( long n ) { // base case if ( n == 0 || n == 1 ) return n; // recursive step else return fibonacci( n - 1 ) + fibonacci( n - 2 ); } // end method fibonacci Note why this would be extremely inefficient
26
26 Recursive Fibonacci Program return + + return 1 fibonacci( 2 )fibonacci( 1 ) fibonacci( 0 ) return 0 fibonacci( 3 )
27
27 Recursion vs. Iteration Both the recursive functions shown can be done with either for or while loops In fact they are done more efficiently iteratively Recursion has overhead Processor time Memory space General rule: If it can be done either recursively or iteratively … choose iteratively
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.