27
Methods Chapter 6

Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

Embed Size (px)

Citation preview

Page 1: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

Methods

Chapter 6

Page 2: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

2

Program Modules in Java

What we call "functions" in C++ are called "methods" in JavaPurpose• 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

Page 3: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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

Page 4: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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 )

Page 5: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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

Page 6: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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

Page 7: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

7

Constants

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

Page 8: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

8

Method Declaration Syntaxmodifiers returnType methodName

(parameterDeclaration){ statements}

modifiers : describers (public, private, etc.)

returnType : type of value returned by method, or void if it does not return a valuemethodName : identifier that names the methodparameterDeclaration : list of parameters, separated by commasstatements : define the behavior of the method

Page 9: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

9

Method Declaration

View declaration of methods in a class for finding maximums, Fig. 6.3• Note method for input, call of method maximum

• Note method for actual determining of maximum

View test program, Fig 6.4• Note declaration of instance of new class• Note call of class methods

Page 10: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

10

Alternative Method Declaration

View alternative solution

Declare methods in the application

Have them follow method main()• Although they can be anywhere in the class

Note they must be static

Page 11: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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

Note: static methods cannot call non-static methods of the same

class directly

Page 12: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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

Page 13: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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()

Page 14: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

14

Argument PromotionPromotion rules

• Specify how to convert types without data loss

Type Valid promotions

double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double (but not char) byte short, int, long, float or double (but not char) boolean None (boolean values are not considered to be numbers in Java)

Type Valid promotions

double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double (but not char) byte short, int, long, float or double (but not char) boolean None (boolean values are not considered to be numbers in Java)

Page 15: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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 packages

Page 16: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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 Random• Note Figure 6.7 and Figure 6.8

Page 17: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

17

Game of ChanceRules 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 pointKeep rolling dice until…• Sum matches player point

• Player wins• Sum equals 7

• Player loses

Page 18: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

18

Game of Chance

Note the adapted version of Figure 6.9• An application

Note• Private class variables• Public methods• The toUpperClass function requires Character. (a non instantiating class)

Page 19: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

19

Scope of DeclarationsScope of a parameter is body of method where declaration appearsScope of local variable is from point of declaration to end of blockScope of label in labeled break/continue is statement enclosed by labeled statementScope of local-variable in initialization of for( ) is for body of for and rest of headerScope of method or field of class is body of class

View Figure 6.11View Figure 6.11

Page 20: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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 scopes• Figure 6.12 Test program

Page 21: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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 class• Figure 6.14 Overload test program

Page 22: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

22

RecursionRecursive method

Calls itself (directly or indirectly) through another methodMethod knows how to solve only a base caseMethod divides problem• Base case• Simpler problem – Method now divides simpler

problem until solvable

Recursive callRecursive step

Page 23: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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! 5 * 4!

Recursive Evaluation of 5!

Page 24: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

24

Recursive Factorial Program

Function factorial() in Figure 6.15

Note• Initial call to factorial()• Anchor or base case• Recursive call

Page 25: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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

Page 26: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

26

Recursive Fibonacci Program

return

return

+

+ return 1

return 1

fibonacci( 2 ) fibonacci( 1 )

fibonacci( 1 ) fibonacci( 0 )

return 0

fibonacci( 3 )

Page 27: Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This

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