chapter 6 - methods

62
2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math-Class Methods 6.4 Method Declarations 6.5 Argument Promotion 6.6 Java API Packages 6.7 Random-Number Generation 6.8 Example: A Game of Chance 6.9 Scope of Declarations 6.10 Methods of Class JApplet 6.11 Method Overloading 6.12 Recursion 6.13 Example Using Recursion: The Fibonacci Series 6.14 Recursion vs. Iteration 6.15 (Optional Case Study) Thinking About Objects: Identifying Class Operations

Upload: isabelle-duncan

Post on 03-Jan-2016

15 views

Category:

Documents


0 download

DESCRIPTION

Chapter 6 - Methods. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

1

Chapter 6 - MethodsOutline6.1 Introduction6.2 Program Modules in Java6.3 Math-Class Methods6.4 Method Declarations 6.5 Argument Promotion6.6 Java API Packages6.7 Random-Number Generation6.8 Example: A Game of Chance6.9 Scope of Declarations 6.10 Methods of Class JApplet 6.11 Method Overloading 6.12 Recursion 6.13 Example Using Recursion: The Fibonacci Series 6.14 Recursion vs. Iteration 6.15 (Optional Case Study) Thinking About Objects: Identifying Class Operations

Page 2: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

2

6.1 Introduction

• Modules– Small pieces of a problem

• e.g., divide and conquer

– Facilitate design, implementation, operation and maintenance of large programs

Page 3: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

3

6.2 Program Modules in Java

• Modules in Java– Methods

– Classes

• Java API provides several modules• Programmers can also create modules

– e.g., programmer-defined methods

• Methods– Invoked by a method call

– Returns a result to calling method (caller)

– Similar to a boss (caller) asking a worker (called method) to complete a task

Page 4: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

4

Fig. 6.1 Hierarchical boss-method/worker-method relationship.

boss

worker1 worker2 worker3

worker4 worker5

Page 5: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

5

6.3 Math-Class Methods

• Class java.lang.Math– Provides common mathematical calculations

– Calculate the square root of 900.0:• Math.sqrt( 900.0 )

– Method sqrt belongs to class Math• Dot (.) allows access to method sqrt

– The argument 900.0 is located inside parentheses

Page 6: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

6

Method Description Example abs( x ) absolute value of x (this method also has float, int and long versions) abs( 23.7 ) is 23.7

abs( 0.0 ) is 0.0 abs( -23.7 ) is 23.7

ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x (x is in radians) cos( 0.0 ) is 1.0 exp( x ) exponential method ex exp( 1.0 ) is 2.71828

exp( 2.0 ) is 7.38906 floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0

floor( -9.8 ) is -10.0 log( x ) natural logarithm of x (base e) log( Math.E ) is 1.0

log( Math.E * Math.E ) is 2.0 max( x, y ) larger value of x and y (this method also has float, int and long

versions) max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3

min( x, y ) smaller value of x and y (this method also has float, int and long versions)

min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7

pow( x, y ) x raised to the power y (xy) pow( 2.0, 7.0 ) is 128.0 pow( 9.0, 0.5 ) is 3.0

sin( x ) trigonometric sine of x (x is in radians) sin( 0.0 ) is 0.0 sqrt( x ) square root of x sqrt( 900.0 ) is 30.0

sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x (x is in radians) tan( 0.0 ) is 0.0 Fig. 6.2 Math-class methods.

Page 7: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

7

6.4 Methods Declarations

• Methods– Allow programmers to modularize programs

• Makes program development more manageable

• Software reusability

• Avoid repeating code

– Local variables• Declared in method declaration

– Parameters• Communicates information between methods via method calls

Page 8: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

8

6.4 Method Declarations (Cont.)

• Programmers can write customized methods

Page 9: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline9

SquareIntegers.java

Line 21Declare result to store square of number

Line 26Method init invokes method square

Line 26Method square returns int that result stores

1 // Fig. 6.3: SquareIntegers.java2 // Creating and using a programmer-defined method.3 import java.awt.Container;4 5 import javax.swing.*;6 7 public class SquareIntegers extends JApplet {8 9 // set up GUI and calculate squares of integers from 1 to 1010 public void init()11 {12 // JTextArea to display results 13 JTextArea outputArea = new JTextArea();14 15 // get applet's content pane (GUI component display area)16 Container container = getContentPane(); 17 18 // attach outputArea to container19 container.add( outputArea ); 20 21 int result; // store result of call to method square22 String output = ""; // String containing results23 24 // loop 10 times25 for ( int counter = 1; counter <= 10; counter++ ) {26 result = square( counter ); // method call27 28 // append result to String output 29 output += "The square of " + counter + " is " + result + "\n";30 31 } // end for

Declare result to store square of number

Method square returns int that result stores

Method init invokes method square (next slide)

Page 10: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline10

SquareIntegers.java

Line 38y is the parameter of method square

Line 40Method square returns the square of y

32 33 outputArea.setText( output ); // place results in JTextArea34 35 } // end method init36 37 // square method declaration 38 public int square( int y ) 39 { 40 return y * y; // return square of y41 42 } // end method square 43 44 } // end class SquareIntegers

y is the parameter of method square

Method square returns the square of y

Page 11: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

11

6.4 Method Declarations (cont.)

• General format of method declaration:

return-value-type method-name( parameter1, parameter2, …, parameterN ){ declarations and statements}

• Method can also return values: return expression;

Page 12: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline12

Maximum.java

Lines 13-18User inputs three Strings

Lines 21-23Convert Strings to doubles

Line 25Method init passes doubles as arguments to method maximum

1 // Fig. 6.4: MaximumTest.java2 // Finding the maximum of three floating-point numbers.3 import java.awt.Container;4 5 import javax.swing.*;6 7 public class MaximumTest extends JApplet {8 9 // initialize applet by obtaining user input and creating GUI10 public void init()11 {12 // obtain user input13 String s1 = JOptionPane.showInputDialog(14 "Enter first floating-point value" );15 String s2 = JOptionPane.showInputDialog(16 "Enter second floating-point value" );17 String s3 = JOptionPane.showInputDialog(18 "Enter third floating-point value" );19 20 // convert user input to double values21 double number1 = Double.parseDouble( s1 );22 double number2 = Double.parseDouble( s2 );23 double number3 = Double.parseDouble( s3 );24 25 double max = maximum( number1, number2, number3 ); // method call26 27 // create JTextArea to display results28 JTextArea outputArea = new JTextArea();29 30 // display numbers and maximum value 31 outputArea.setText( "number1: " + number1 + "\nnumber2: " + 32 number2 + "\nnumber3: " + number3 + "\nmaximum is: " + max );33

User inputs three Strings

Convert Strings to doubles

Method init passes doubles as arguments to

method maximum

Page 13: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline13

Maximum.java

Line 46Method maximum returns value from method max of class Math

34 // get applet's GUI component display area35 Container container = getContentPane();36 37 // attach outputArea to Container c38 container.add( outputArea );39 40 } // end method init41 42 // maximum method uses Math class method max to help 43 // determine maximum value 44 public double maximum( double x, double y, double z )45 { 46 return Math.max( x, Math.max( y, z ) ); 47 48 } // end method maximum 49 50 } // end class Maximum

Method maximum returns value from method max of class Math

Page 14: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

14

6.5 Argument Promotion

• Coercion of arguments

– Forcing arguments to appropriate type to pass to method

• e.g., System.out.println( Math.sqrt( 4 ) );

– Evaluates Math.sqrt( 4 )

– Then evaluates System.out.println()

• Promotion rules

– Specify how to convert types without data loss

Page 15: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

15

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 byte short, int, long, float or double boolean None (boolean values are not considered to be

numbers in Java) Fig. 6.5 Allowed promotions for primitive types.

Page 16: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

16

6.6 Java API Packages

• Packages

– Classes grouped into categories of related classes

– Promotes software reuse

– import statements specify classes used in Java programs

• e.g., import javax.swing.JApplet;

Page 17: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

17

Package Description java.applet The Java Applet Package contains the Applet class and several interfaces that enable applet/browser interaction

and the playing of audio clips. In Java 2, class javax.swing.JApplet is used to define an applet that uses the Swing GUI components.

java.awt The Java Abstract Window Toolkit Package contains the classes and interfaces required to create and manipulate GUIs in Java 1.0 and 1.1. In Java 2, the Swing GUI components of the javax.swing packages are often used instead.

java.awt.event The Java Abstract Window Toolkit Event Package contains classes and interfaces that enable event handling for GUI components in both the java.awt and javax.swing packages.

java.io The Java Input/Output Package contains classes that enable programs to input and output data (see Chapter 17, Files and Streams).

java.lang The Java Language Package contains classes and interfaces (discussed throughout this text) that are required by many Java programs. This package is imported by the compiler into all programs.

java.net The Java Networking Package contains classes that enable programs to communicate via networks (see Chapter 18, Networking).

java.text The Java Text Package contains classes and interfaces that enable a Java program to manipulate numbers, dates, characters and strings. The package provides many of Java’s internationalization capabilities that enable a program to be customized to a specific locale (e.g., an applet may display strings in different languages, based on the user’s country).

java.util The Java Utilities Package contains utility classes and interfaces, such as date and time manipulations, random-number processing capabilities with class Random, storing and processing large amounts of data and breaking strings into smaller pieces called tokens with class StringTokenizer (see Chapter 20; Data Structures, Chapter 21, Java Utilities Package and Bit Manipulation; and Chapter 22, Collections).

javax.swing The Java Swing GUI Components Package contains classes and interfaces for Java’s Swing GUI components that provide support for portable GUIs.

javax.swing.event The Java Swing Event Package contains classes and interfaces that enable event handling for GUI components in package javax.swing.

Fig. 6.6 Java API packages (a subset).

Page 18: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

18

6.7 Random-Number Generation

• Java random-number generators

– Math.random()

• ( int ) ( Math.random() * 6 )

– Produces integers from 0 - 5

– Use a seed for different random-number sequences

Page 19: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline19

RandomIntegers.java

Line 16Produce integers in range 1-6

Line 16Math.random returns doubles. We cast the double as an int

1 // Fig. 6.7: RandomIntegers.java2 // Shifted, scaled random integers.3 import javax.swing.JOptionPane;4 5 public class RandomIntegers {6 7 public static void main( String args[] )8 {9 int value;10 String output = "";11 12 // loop 20 times13 for ( int counter = 1; counter <= 20; counter++ ) {14 15 // pick random integer between 1 and 6 16 value = 1 + ( int ) ( Math.random() * 6 );17 18 output += value + " "; // append value to output19 20 // if counter divisible by 5, append newline to String output21 if ( counter % 5 == 0 )22 output += "\n";23 24 } // end for25

Produce integers in range 1-6

Math.random returns doubles. We cast the double as an int

Page 20: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline20

RandomIntegers.java

26 JOptionPane.showMessageDialog( null, output, 27 "20 Random Numbers from 1 to 6", 28 JOptionPane.INFORMATION_MESSAGE );29 30 System.exit( 0 ); // terminate application31 32 } // end main33 34 } // end class RandomIntegers

Page 21: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline21

RollDie.java

Line 14Produce integers in range 1-6

Lines 17-43Increment appropriate frequency counter, depending on randomly generated number

1 // Fig. 6.8: RollDie.java2 // Roll a six-sided die 6000 times.3 import javax.swing.*;4 5 public class RollDie {6 7 public static void main( String args[] )8 {9 int frequency1 = 0, frequency2 = 0, frequency3 = 0,10 frequency4 = 0, frequency5 = 0, frequency6 = 0, face;11 12 // summarize results13 for ( int roll = 1; roll <= 6000; roll++ ) {14 face = 1 + ( int ) ( Math.random() * 6 );15 16 // determine roll value and increment appropriate counter17 switch ( face ) {18 19 case 1:20 ++frequency1;21 break; 22 23 case 2:24 ++frequency2;25 break;26 27 case 3:28 ++frequency3;29 break;30

Produce integers in range 1-6

Increment appropriate frequency counter, depending on randomly generated number

Page 22: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline22

RollDie.java

31 case 4:32 ++frequency4;33 break;34 35 case 5:36 ++frequency5;37 break;38 39 case 6:40 ++frequency6;41 break;42 43 } // end switch44 45 } // end for46 47 JTextArea outputArea = new JTextArea();48 49 outputArea.setText( "Face\tFrequency" + "\n1\t" + frequency1 + 50 "\n2\t" + frequency2 + "\n3\t" + frequency3 + 51 "\n4\t" + frequency4 + "\n5\t" + frequency5 + 52 "\n6\t" + frequency6 );53 54 JOptionPane.showMessageDialog( null, outputArea,55 "Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE );56 57 System.exit( 0 ); // terminate application58 59 } // end main60 61 } // end class RollDie

Page 23: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

23

Page 24: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

24

6.8 Example: A Game of Chance

• Craps simulation– 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

Page 25: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline25

Craps.java

Line 24Method init starts JApplet and initializes GUI

1 // Fig. 6.9: Craps.java2 // Craps.3 import java.awt.*; // Container, FlowLayout 4 import java.awt.event.*; // ActionEvent, ActionListener5 6 import javax.swing.*; // JApplet, JButton, JLabel, JTextField7 8 public class Craps extends JApplet implements ActionListener {9 10 // constant variables for game status 11 final int WON = 0, LOST = 1, CONTINUE = 2; 12 13 boolean firstRoll = true; // true if first roll of dice14 int sumOfDice = 0; // sum of the dice15 int myPoint = 0; // point if no win or loss on first roll16 int gameStatus = CONTINUE; // game not over yet17 18 // graphical user interface components 19 JLabel die1Label, die2Label, sumLabel, pointLabel; 20 JTextField die1Field, die2Field, sumField, pointField;21 JButton rollButton; 22 23 // set up GUI components24 public void init()25 {26 // obtain content pane and change its layout to FlowLayout27 Container container = getContentPane(); 28 container.setLayout( new FlowLayout() ); 29

Method init starts JApplet and initializes GUI (Chapter 12

covers GUI in detail)

Page 26: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline26

Craps.java

Lines 33 JTextField that output dice results Line 40 JTextField that output dice resultsLine 47 JTextField that outputs sum of dice Line 54 JTextField that outputs player’s point

30 // create label and text field for die 131 die1Label = new JLabel( "Die 1" ); 32 container.add( die1Label ); 33 die1Field = new JTextField( 10 ); 34 die1Field.setEditable( false ); 35 container.add( die1Field ); 36 37 // create label and text field for die 238 die2Label = new JLabel( "Die 2" );39 container.add( die2Label );40 die2Field = new JTextField( 10 );41 die2Field.setEditable( false );42 container.add( die2Field );43 44 // create label and text field for sum45 sumLabel = new JLabel( "Sum is" );46 container.add( sumLabel );47 sumField = new JTextField( 10 );48 sumField.setEditable( false );49 container.add( sumField );50 51 // create label and text field for point52 pointLabel = new JLabel( "Point is" );53 container.add( pointLabel );54 pointField = new JTextField( 10 );55 pointField.setEditable( false );56 container.add( pointField );57

JTextField that outputs sum of dice

JTextField that outputs player’s point

JTextField that output dice results

JTextField that output dice results

Page 27: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline27

Craps.java

Line 59JButton for rolling dice

Line 66Method invoked when user presses JButton

Line 68Invoke method rollDice

Lines 76-80If sum is 7 or 11, user wins

Lines 83-88If user rolls 2, 3 or 12, user loses

58 // create button user clicks to roll dice59 rollButton = new JButton( "Roll Dice" ); 60 rollButton.addActionListener( this ); 61 container.add( rollButton ); 62 63 } // end method init64 65 // process one roll of dice66 public void actionPerformed( ActionEvent actionEvent )67 {68 sumOfDice = rollDice(); // roll dice69 70 // first roll of dice71 if ( firstRoll ) { 72 73 switch ( sumOfDice ) {74 75 // win on first roll76 case 7: 77 case 11:78 gameStatus = WON;79 pointField.setText( "" ); // clear point field80 break;81 82 // lose on first roll83 case 2: 84 case 3: 85 case 12:86 gameStatus = LOST;87 pointField.setText( "" ); // clear point field88 break;

If sum is 7 or 11, user wins

If user rolls 2, 3 or 12, user loses

JButton for rolling dice

Method invoked when user presses JButton

Invoke method rollDice

Page 28: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline28

Craps.java

Lines 91-96If sum is 4, 5, 6, 8, 9 or 10, that sum is the point

Lines 105-109If sum equals point, user wins; If sum equals 7, user loses

89 90 // remember point91 default: 92 gameStatus = CONTINUE;93 myPoint = sumOfDice;94 pointField.setText( Integer.toString( myPoint ) );95 firstRoll = false;96 break;97 98 } // end switch 99 100 } // end if part of if...else101 102 else { // subsequent roll of dice103 104 // determine game status105 if ( sumOfDice == myPoint ) // win by making point106 gameStatus = WON;107 else108 if ( sumOfDice == 7 ) // lose by rolling 7109 gameStatus = LOST;110 111 } // end else part of if...else112 113 displayMessage(); // display message indicating game status114 115 } // end method actionPerformed116

If sum equals point, user wins; If sum equals 7, user loses

If sum is 4, 5, 6, 8, 9 or 10, that sum is the point

Page 29: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline29

Craps.java

Lines 121-122Method rollDice uses Math.random to simulate rolling two dice

Line 131return dice sum

117 // roll dice, calculate sum and display results118 public int rollDice()119 {120 // pick random die values121 int die1 = 1 + ( int ) ( Math.random() * 6 ); 122 int die2 = 1 + ( int ) ( Math.random() * 6 );123 124 int sum = die1 + die2; // sum die values125 126 // display results in textfields127 die1Field.setText( Integer.toString( die1 ) );128 die2Field.setText( Integer.toString( die2 ) );129 sumField.setText( Integer.toString( sum ) ); 130 131 return sum; // return sum of dice132 133 } // end method rollDice134 135 // determine game status; display appropriate message in status bar136 public void displayMessage()137 {138 // game should continue139 if ( gameStatus == CONTINUE )140 showStatus( "Roll again." );141

return dice sum

Method rollDice uses Math.random to simulate rolling two dice

Page 30: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline30

Craps.java

142 else { // game won or lost143 144 if ( gameStatus == WON )145 showStatus( "Player wins. Click Roll Dice to play again." ); 146 else 147 showStatus( "Player loses. Click Roll Dice to play again." );148 149 firstRoll = true; // next roll is first roll of new game150 151 } // end else part of if...else152 153 } // end method displayMessage154 155 } // end class Craps

Page 31: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline31

Craps.java

Page 32: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

32

6.9 Scope of Declarations

• Scope– Portion of the program that can reference an entity by its

name

– Basic scope rules• Scope of a parameter declaration

• Scope of a local-variable declaration

• Scope of a label in a labeled break or continue statement

• Scope of a local-variable declaration that appears in the initialization section of a for statement’s header

• Scope of a method or field of a class

Page 33: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline33

Scoping.java

Line 11field x

Line 26Local variable x

Line 28Method start uses local variable x

1 // Fig. 6.10: Scoping.java2 // A scoping example.3 import java.awt.Container;4 5 import javax.swing.*;6 7 public class Scoping extends JApplet {8 JTextArea outputArea;9 10 // field that is accessible to all methods of this class11 int x = 1; 12 13 // create applet's GUI14 public void init()15 {16 outputArea = new JTextArea();17 Container container = getContentPane(); 18 container.add( outputArea );19 20 } // end method init21 22 // method start called after init completes; start calls23 // methods useLocal and useField24 public void start()25 {26 int x = 5; // local variable in method start that shadows field x27 28 outputArea.append( "local x in start is " + x );29

Field x has class scope

Local variable x has block scope

Method start uses local variable x

Page 34: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline34

Scoping.java

Line 42Recreate variable x and initialize it to 25

Lines 40-50Method useLocal uses local variable x

30 useLocal(); // useLocal has local x31 useField(); // useInstance uses Scoping's field x32 useLocal(); // useLocal reinitializes local x33 useField(); // Scoping's field x retains its value34 35 outputArea.append( "\n\nlocal x in start is " + x );36 37 } // end method start38 39 // useLocal creates and initializes local variable x during each call40 public void useLocal()41 {42 int x = 25; // initialized each time useLocal is called43 44 outputArea.append( "\n\nlocal x in useLocal is " + x +45 " after entering useLocal" );46 ++x;47 outputArea.append( "\nlocal x in useLocal is " + x +48 " before exiting useLocal" );49 50 } // end method useLocal51

Re-create variable x and initialize it to 25

Method useLocal uses local variable x

Page 35: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline35

Scoping.java

Lines 53-61Method useField uses field x

52 // useField modifies Scoping's field x during each call53 public void useField()54 {55 outputArea.append( "\n\nfield x is " + x +56 " on entering useField" );57 x *= 10;58 outputArea.append( "\nfield x is " + x +59 " on exiting useField" );60 61 } // end method useInstance62 63 } // end class Scoping

Method useField uses field x

Page 36: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

36

6.16 Methods of Class JApplet

• Java API defines several JApplet methods– Defining methods of Fig. 6.11 in a JApplet is called

overriding those methods.

Page 37: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

37

Method When the method is called and its purpose public void init()

This method is called once by the applet container when an applet is loaded for execution. It performs initialization of an applet. Typical actions performed here are initializing fields, creating GUI components, loading sounds to play, loading images to display (see Chapter 19, Multimedia) and creating threads (see Chapter 16, Multithreading).

public void start()

This method is called after the init method completes execution. In addition, if the browser user visits another Web site and later returns to the HTML page on which the applet resides, method start is called again. The method performs any tasks that must be completed when the applet is loaded for the first time and that must be performed every time the HTML page on which the applet resides is revisited. Typical actions performed here include starting an animation (see Chapter 19) and starting other threads of execution (see Chapter 16).

public void paint( Graphics g )

This drawing method is called after the init method completes execution and the start method has started. It is also called every time the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen and later uncovers the applet, the paint method is called. Typical actions performed here involve drawing with the Graphics object g that is passed to the paint method by the applet container.

public void stop()

This method is called when the applet should stop executing—normally, when the user of the browser leaves the HTML page on which the applet resides. The method performs any tasks that are required to suspend the applet’s execution. Typical actions performed here are to stop execution of animations and threads.

public void destroy()

This method is called when the applet is being removed from memory—normally, when the user of the browser exits the browsing session (i.e., closes all browser windows). The method performs any tasks that are required to destroy resources allocated to the applet.

Fig. 6.11 JApplet methods that the applet container calls during an applet’s execution.

Page 38: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

38

6.15 Method Overloading

• Method overloading– Several methods of the same name

– Different parameter set for each method• Number of parameters

• Parameter types

Page 39: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline39

MethodOverload.java

Lines 22-29Method square receives an int as an argument

1 // Fig. 6.12: MethodOverload.java2 // Using overloaded methods3 import java.awt.Container;4 5 import javax.swing.*;6 7 public class MethodOverload extends JApplet {8 9 // create GUI and call each square method10 public void init()11 {12 JTextArea outputArea = new JTextArea();13 Container container = getContentPane();14 container.add( outputArea );15 16 outputArea.setText( "The square of integer 7 is " + square( 7 ) +17 "\nThe square of double 7.5 is " + square( 7.5 ) );18 19 } // end method init20 21 // square method with int argument 22 public int square( int intValue ) 23 { 24 System.out.println( "Called square with int argument: " +25 intValue ); 26 27 return intValue * intValue; 28 29 } // end method square with int argument 30

Method square receives an int as an argument

Page 40: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline40

MethodOverload.java

Lines 32-39Overloaded method square receives a double as an argument

31 // square method with double argument 32 public double square( double doubleValue ) 33 { 34 System.out.println( "Called square with double argument: " +35 doubleValue ); 36 37 return doubleValue * doubleValue; 38 39 } // end method square with double argument 40 41 } // end class MethodOverload

Called square with int argument: 7Called square with double argument: 7.5

Overloaded method square receives a double as an argument

Page 41: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline41

MethodOverload.java

Lines 8 and 15Compiler cannot distinguish between methods with identical names and parameter sets

Fig. 6.17 Compiler error messages generated from overloaded methods with identical parameter lists and different return types.

1 // Fig. 6.13: MethodOverload.java2 // Overloaded methods with identical signatures.3 import javax.swing.JApplet;4 5 public class MethodOverload extends JApplet {6 7 // declaration of method square with int argument8 public int square( int x )9 {10 return x * x;11 }12 13 // second declaration of method square 14 // with int argument causes syntax error15 public double square( int y ) 16 { 17 return y * y; 18 } 19 20 } // end class MethodOverload

MethodOverload.java:15: square(int) is already defined in MethodOverload public double square( int y ) ^1 error

Compiler cannot distinguish between methods with identical names and

parameter sets

Page 42: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

42

6.12 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

Page 43: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

43

Fig. 6.14 Recursive evaluation of 5!.

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!

Page 44: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline44

FactorialTest.java

Line 21Invoke method factorial

1 // Fig. 6.15: FactorialTest.java2 // Recursive factorial method.3 import java.awt.*;4 5 import javax.swing.*;6 7 public class FactorialTest extends JApplet {8 JTextArea outputArea;9 10 // create GUI and calculate factorials of 0-1011 public void init()12 {13 outputArea = new JTextArea();14 15 Container container = getContentPane();16 container.add( outputArea );17 18 // calculate the factorials of 0 through 1019 for ( long counter = 0; counter <= 10; counter++ )20 outputArea.append( counter + "! = " +21 factorial( counter ) + "\n" );22 23 } // end method init24

Invoke method factorial

Page 45: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline45

FactorialTest.java

Lines 29-30Test for base case (method factorial can solve base case)

Line 34Else return simpler problem that method factorial might solve in next recursive call

25 // recursive declaration of method factorial 26 public long factorial( long number ) 27 { 28 // base case 29 if ( number <= 1 ) 30 return 1; 31 32 // recursive step 33 else 34 return number * factorial( number - 1 );35 36 } // end method factorial 37 38 } // end class FactorialTest

Test for base case (method factorial can solve base case)

Else return simpler problem that method factorial might solve

in next recursive call

Page 46: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

46

6.13 Example Using Recursion: The Fibonacci Series

• Fibonacci series– Each number in the series is sum of two previous numbers

• e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21…

fibonacci(0) = 0 fibonacci(1) = 1fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 1 )

• fibonacci(0) and fibonacci(1) are base cases

– Golden ratio (golden mean)

Page 47: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline47

FibonacciTest.java

1 // Fig. 6.16: FibonacciTest.java2 // Recursive fibonacci method.3 import java.awt.*;4 import java.awt.event.*;5 6 import javax.swing.*;7 8 public class FibonacciTest extends JApplet implements ActionListener {9 JLabel numberLabel, resultLabel;10 JTextField numberField, resultField;11 12 // set up applet’s GUI13 public void init()14 {15 // obtain content pane and set its layout to FlowLayout16 Container container = getContentPane();17 container.setLayout( new FlowLayout() );18 19 // create numberLabel and attach it to content pane20 numberLabel = new JLabel( "Enter an integer and press Enter" );21 container.add( numberLabel );22 23 // create numberField and attach it to content pane24 numberField = new JTextField( 10 );25 container.add( numberField );26 27 // register this applet as numberField’s ActionListener28 numberField.addActionListener( this ); 29

Page 48: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline48

FibonacciTest.java Line 43Method actionPerformed is invoked when user presses EnterLine 45We use long, because Fibonacci numbers become large quicklyLines 48-53Pass user input to method fibonacci

30 // create resultLabel and attach it to content pane31 resultLabel = new JLabel( "Fibonacci value is" );32 container.add( resultLabel );33 34 // create numberField, make it uneditable35 // and attach it to content pane36 resultField = new JTextField( 15 );37 resultField.setEditable( false );38 container.add( resultField );39 40 } // end method init41 42 // obtain user input and call method fibonacci43 public void actionPerformed( ActionEvent event )44 { 45 long number, fibonacciValue;46 47 // obtain user’s input and convert to long48 number = Long.parseLong( numberField.getText() );49 50 showStatus( "Calculating ..." ); 51 52 // calculate fibonacci value for number user input53 fibonacciValue = fibonacci( number ); 54 55 // indicate processing complete and display result56 showStatus( "Done." ); 57 resultField.setText( Long.toString( fibonacciValue ) );58 59 } // end method actionPerformed60

Method actionPerformed is invoked when user presses Enter

We use long, because Fibonacci numbers

become large quickly

Pass user input to method fibonacci

Page 49: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline49

FibonacciTest.java

Lines 65-66Test for base case (method fibonacci can solve base case)

Lines 69-70Else return simpler problem that method fibonacci might solve in next recursive call

61 // recursive declaration of method fibonacci 62 public long fibonacci( long n ) 63 { 64 // base case 65 if ( n == 0 || n == 1 ) 66 return n; 67 68 // recursive step 69 else 70 return fibonacci( n - 1 ) + fibonacci( n - 2 );71 72 } // end method fibonacci 73 74 } // end class FibonacciTest

Else return simpler problem that method fibonacci might solve

in next recursive call

Test for base case (method fibonacci can solve base case)

Page 50: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline50

FibonacciTest.java

Page 51: Chapter 6 - Methods

2003 Prentice Hall, Inc.All rights reserved.

Outline51

FibonacciTest.java

Page 52: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

52

Fig. 6.17 Set of recursive calls for fibonacci (3).

return

return

+

+ return 1

return 1

fibonacci( 2 ) fibonacci( 1 )

fibonacci( 1 ) fibonacci( 0 )

return 0

fibonacci( 3 )

Page 53: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

53

6.14 Recursion vs. Iteration

• Iteration– Uses repetition structures (for, while or do…while)

– Repetition through explicitly use of repetition structure

– Terminates when loop-continuation condition fails

– Controls repetition by using a counter

• Recursion– Uses selection structures (if, if…else or switch)

– Repetition through repeated method calls

– Terminates when base case is satisfied

– Controls repetition by dividing problem into simpler one

Page 54: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

54

6.14 Recursion vs. Iteration (cont.)

• Recursion– More overhead than iteration

– More memory intensive than iteration

– Can also be solved iteratively

– Often can be implemented with only a few lines of code

Page 55: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

55

Chapter Recursion examples and exercises 6 Factorial method (Fig. 6.15), Fibonacci method (Fig. 6.16), Raising an integer to an

integer power (Exercise 6.36), Towers of Hanoi (Exercise 6.37), Visualizing recursion (Exercise 6.39), Greatest common divisor (Exercise 6.40), What does this method do?(Exercise 6.43), Find the error in the recursive method (Exercise 6.45)

7 What does this program do? (Exercise 7.16), What does this program do? (Exercise 7.19), Determine whether a string is a palindrome (Exercise 7.32), Linear search (Exercise 7.33), Binary search (Exercise 7.34), Eight Queens (Exercise 7.35) Print an array (Exercise 7.36), Print an array backward (Exercise 7.37), Minimum value in an array (Exercise 7.38), Quicksort (Exercise 7.39), Maze traversal (Exercise 7.40)

20 Binary-tree insert (Fig. 20.17), Preorder traversal of a binary tree (Fig. 20.17), Inorder traversal of a binary tree (Fig. 20.17), Postorder traversal of a binary tree (Fig. 20.17), Print a linked list backward (Exercise 20.20), Search a linked list (Exercise 20.21)

Fig. 6.18 Summary of recursion examples and exercises in this text.

Page 56: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

566.15 (Optional Case Study) Thinking About Objects: Identifying Class

Operations• Class operations

– Also known as behaviors

– Service the class provides to “clients” (users) of that class• e.g., radio’s operations

– Setting its station or volume

Page 57: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

57

6.15 Thinking About Objects (cont.)

• Deriving class operations– Use problem statement

• Identify verbs and verb phrases

• Verbs can help determine class operations

Page 58: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

58

Class Verb phrases Elevator moves to other floor, arrives at a floor, resets elevator

button, rings elevator bell, signals its arrival, opens its door, closes its door

ElevatorShaft turns off light, turns on light, resets floor button Person walks on floor, presses floor button, presses elevator

button, rides elevator, enters elevator, exits elevator Floor [none in the problem statement] FloorButton requests elevator ElevatorButton closes elevator door, signals elevator to move to opposite

floor FloorDoor signals person to enter elevator (by opening) ElevatorDoor signals person to exit elevator (by opening), opens floor

door, closes floor door Bell [none in the problem statement] Light [none in the problem statement] Fig. 6.19 Verb phrases for each class in simulator.

Page 59: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

59

6.15 Thinking About Objects (cont.)

• Deriving class operations– Verbs can help determine class operations

• e.g., verb phrase “resets elevator button”

– Elevator informs ElevatorButton to reset

– ElevatorButton needs method resetButton• e.g., verb phrase “signal its arrival”

– Elevator informs ElevatorDoor to open

– ElevatorDoor needs method openDoor

Page 60: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

60

6.17 Thinking About Objects (cont.)

• Deriving class operations– Not all verbs determine class operations

• e.g., verb phrase “the elevator arrives at a floor”

– Elevator decides when to arrive

• (after traveling 5 seconds)

– i.e., no object causes Elevator to arrive

– Elevator does not need to provide “arrival” service for other objects

– arriveElevator is not a valid method (operation)

• We do not include method arriveElevator

Page 61: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

61

6.17 Thinking About Objects (cont.)

• Store methods (operations) in UML class diagram– Place class methods in bottom compartment of that class

Page 62: Chapter 6 - Methods

2003 Prentice Hall, Inc. All rights reserved.

62

Fig 6.20 Classes with attributes and operations.

Floor

floorNumber : Integercapacity : Integer = 1

ElevatorButton

pressed : Boolean = false

resetButton( ) pressButton( )

ElevatorDoor

open : Boolean = false

openDoor( ) closeDoor( )

Light

lightOn : Boolean = false

turnOnLight( ) turnOffLight( )

Bell

ringBell( )

ElevatorShaftPerson

ID : Integermoving : Boolean = true

doorOpened( )

Elevator

moving : Boolean = falsesummoned : Boolean = falsecurrentFloor : Integer = 1destinationFloor : Integer = 2capacity : Integer = 1travelTime : Integer = 5

ride( ) requestElevator( )enterElevator( )exitElevator( )departElevator( )

FloorButton

pressed : Boolean = false

resetButton( ) pressButton( )

FloorDoor

open : Boolean = false

openDoor( ) closeDoor( )