Download Chapter 6

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
Chapter 6 - Methods
Outline
6.1
6.2
6.3
6.4
6.5
6.6
6.9
6.10
6.11
6.12
6.14
Introduction
Program Modules in Java
Math-Class Methods
Method Declarations
Argument Promotion
Java API Packages
Scope of Declarations
Methods of Class JApplet
Method Overloading
Recursion
Recursion vs. Iteration
 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
 2003 Prentice Hall, Inc. All rights reserved.
3
6.2
Program Modules in Java
• Modules in Java
– Methods (functions, procedures in other languages)
– Classes
• Java Application Programming Interface (API)
provides rich collection of classes
• Programmers can also create modules
– promotes software reusability
• 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
 2003 Prentice Hall, Inc. All rights reserved.
4
boss
worker1
worker4
worker2
worker3
worker5
Fig. 6.1 Hierarchical boss-method/worker-method relationship.
 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:
• Math.sqrt( 900.0 )
– Method sqrt belongs to class Math
• Dot (.) allows access to method sqrt
• All Math class methods invoked by
Math.methodName (args)
• No need for import java.lang.*
(automatically imported)
– The argument 900.0 is located inside parentheses
 2003 Prentice Hall, Inc. All rights reserved.
6
Method
abs( x )
ceil( x )
cos( x )
exp( x )
floor( x )
log( x )
max( x, y )
min( x, y )
pow( x, y )
sin( x )
sqrt( x )
tan( x )
Fig. 6.2 Math-class methods.
Description
Example
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
rounds x to the smallest integer not less than x
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
trigonometric cosine of x (x is in radians)
cos( 0.0 ) is 1.0
exponential method ex
exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
rounds x to the largest integer not greater than x
floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
natural logarithm of x (base e)
log( Math.E ) is 1.0
log( Math.E * Math.E ) is 2.0
larger value of x and y (this method also has float, int and long
max( 2.3, 12.7 ) is 12.7
versions)
max( -2.3, -12.7 ) is -2.3
smaller value of x and y (this method also has float, int and long
min( 2.3, 12.7 ) is 2.3
versions)
min( -2.3, -12.7 ) is -12.7
x raised to the power y (xy)
pow( 2.0, 7.0 ) is 128.0
pow( 9.0, 0.5 ) is 3.0
trigonometric sine of x (x is in radians)
sin( 0.0 ) is 0.0
square root of x
sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
trigonometric tangent of x (x is in radians)
tan( 0.0 ) is 0.0
 2003 Prentice Hall, Inc. All rights reserved.
7
6.4
Method 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
 2003 Prentice Hall, Inc. All rights reserved.
8
6.4
Method Declarations (Cont.)
• Programmers can write customized methods
• Each class method can call other methods of that
class (square(x)) without using a class name
(SquareInts.square(x)) or object name
(y.square(x))
 2003 Prentice Hall, Inc. All rights reserved.
9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Outline
// Fig. 6.3: SquareIntegers.java
// Creating and using a programmer-defined method.
import java.awt.Container;
import javax.swing.*;
Declare result to store
square of number
SquareIntegers.
java
public class SquareIntegers extends JApplet {
// set up GUI and calculate squares of integers from 1 to 10
Method init invokes
public void init()
method square (next slide)
{
// JTextArea to display results
JTextArea outputArea = new JTextArea();
// get applet's content pane (GUI component display area)
Container container = getContentPane();
// attach outputArea to container
container.add( outputArea );
int result;
String output = "";
// store result of call to method
// String containing results
Line 21
Declare result to
store square of number
Line 26
Method init invokes
method square
Method square returns int
Line 26
that result
stores
Method square
returns int that
square
result stores
// loop 10 times
for ( int counter = 1; counter <= 10; counter++ ) {
result = square( counter ); // method call
// append result to String output
output += "The square of " + counter + " is " + result + "\n";
} // end for
 2003 Prentice Hall, Inc.
All rights reserved.
10
32
33
34
35
36
37
38
39
40
41
42
43
44
outputArea.setText( output );
// place results in JTextArea
} // end method init
// square method declaration
y is the parameter of
public int square( int y )
method square
{
return (y * y); // return square of y
} // end method square
} // end class SquareIntegers
Method square
returns the square of y
Outline
SquareIntegers.
java
Line 38
y is the parameter of
method square
Line 40
Method square
returns the square of y
 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
return [(expression)];
}
• First line is called “method header”
• Method-name is any valid identifier
• Declarations and statements are the “method
body”
• Method can also return values:
return (expression);
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
12
// Fig. 6.4: MaximumTest.java
// Finding the maximum of three floating-point numbers.
import java.awt.Container;
import javax.swing.*;
Outline
Maximum.java
User inputs three Strings
public class MaximumTest extends JApplet {
// initialize applet by obtaining user input and creating GUI
public void init()
{
// obtain user input
String s1 = JOptionPane.showInputDialog(
"Enter first floating-point value" );
String s2 = JOptionPane.showInputDialog(
"Enter second floating-point value" );
Convert Strings
String s3 = JOptionPane.showInputDialog(
"Enter third floating-point value" );
// convert user input to double values
double number1 = Double.parseDouble( s1 );
double number2 = Double.parseDouble( s2 );
double number3 = Double.parseDouble( s3 );
Lines 13-18
User inputs three
Strings
Lines 21-23
Convert Strings to
doubles
to doubles
Line 25
Method init passes
doubles as
arguments to method
Method maximum
init passes
doubles as arguments to
method maximum
double max = maximum( number1, number2, number3 ); // method call
// create JTextArea to display results
JTextArea outputArea = new JTextArea();
// display numbers and maximum value
outputArea.setText( "number1: " + number1 + "\nnumber2: " +
number2 + "\nnumber3: " + number3 + "\nmaximum is: " + max );
 2003 Prentice Hall, Inc.
All rights reserved.
13
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// get applet's GUI component display area
Container container = getContentPane();
// attach outputArea to Container c
container.add( outputArea );
Outline
Maximum.java
Method maximum returns value
Line 46
from method max of class Math
Method maximum
// maximum method uses Math class method max to help
returns value from
// determine maximum value
method max of class
public double maximum( double x, double y, double z )
Math
{
} // end method init
return ( Math.max( x, Math.max( y, z ) ) );
} // end method maximum
} // end class MaximumTest
 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 ) );
– Math.sqrt expects a double argument
– Evaluates Math.sqrt( 4 )
– Then evaluates System.out.println()
• Promotion rules
– Specify how to convert types without data loss
– Mixed expressions convert all values to “highest” type
– float or double to int results in truncation – cast is required
(int) weight
 2003 Prentice Hall, Inc. All rights reserved.
15
Type
double
float
long
int
char
short
byte
boolean
Valid promotions
None
double
float or double
long, float, or double
int, long, float, or double
int, long, float, or double
short, int, long, float, or double
None (boolean values are not considered to be
numbers in Java)
Fig. 6.5 Allowed promotions for primitive types.
 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;
• Usually import javax.swing.*; to get all classes in
that package
 2003 Prentice Hall, Inc. All rights reserved.
17
Package
java.applet
Description
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, randomnumber 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
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 API packages (a subset).
 2003 Prentice Hall, Inc. All rights reserved.
18
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 is body of method in
which declaration appears
• Scope of a local-variable declaration is from declaration
to end of block
• Scope of a local-variable declaration that appears in the
initialization section of a for statement’s header is
inside the for statement
• Scope of a method or field of a class is entire body of the
class
 2003 Prentice Hall, Inc. All rights reserved.
19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Outline
// Fig. 6.10: Scoping.java
// A scoping example.
import java.awt.Container;
import javax.swing.*;
Field x has class scope
Line 11
field x
public class Scoping extends JApplet {
JTextArea outputArea;
// field that is accessible to all methods of this class
int x = 1;
// create applet's GUI
public void init()
{
outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );
} // end method init
Scoping.java
Line 26
Local variable x
Line 28
Method start uses
local variable x
Local variable x has block scope
// method start called after init completes; start calls
// methods useLocal and useField
Method start uses
public void start()
local variable x
{
int x = 5;
// local variable in method start that shadows field x
outputArea.append( "local x in start is " + x );
 2003 Prentice Hall, Inc.
All rights reserved.
20
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
useLocal();
useField();
useLocal();
useField();
//
//
//
//
Outline
useLocal has local x
useInstance uses Scoping's field x
useLocal reinitializes local x
Scoping's field x retains its value
Scoping.java
outputArea.append( "\n\nlocal x in start is " + x );
} // end method start
Re-create
variable
x x during each call
// useLocal creates and initializes
local
variable
public void useLocal()
and initialize it to 25
{
int x = 25; // initialized each time useLocal is called
outputArea.append( "\n\nlocal
" after entering useLocal"
++x;
outputArea.append( "\nlocal x
" before exiting useLocal"
x in useLocal is " + x +
);
in useLocal is " + x +
);
Line 42
Recreate variable x
and initialize it to 25
Lines 40-50
Method useLocal
uses local variable x
Method useLocal
uses local variable x
} // end method useLocal
 2003 Prentice Hall, Inc.
All rights reserved.
21
52
53
54
55
56
57
58
59
60
61
62
63
// useField modifies Scoping's field x during each call
public void useField()
{
outputArea.append( "\n\nfield x is " + x +
" on entering useField" );
x *= 10;
outputArea.append( "\nfield x is " + x +
" on exiting useField" );
} // end method useInstance
Outline
Scoping.java
Lines 53-61
Method useField
Method useField
uses field x
uses field x
} // end class Scoping
 2003 Prentice Hall, Inc.
All rights reserved.
22
6.10 Methods of Class JApplet
• Java API defines several JApplet methods
– Defining methods of Fig. 6.11 in a JApplet is called
overriding those methods.
– Default versions of each do nothing
 2003 Prentice Hall, Inc. All rights reserved.
23
Method
public void
init()
When the method is called and its purpose
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.
 2003 Prentice Hall, Inc. All rights reserved.
24
6.11 Method Overloading
• Method overloading
– Several methods of the same name that perform similar tasks
– Different parameter set for each method (“signature”)
• Number of parameters
• Parameter types
– Methods cannot differ ONLY in return types
 2003 Prentice Hall, Inc. All rights reserved.
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 6.12: MethodOverload.java
// Using overloaded methods
import java.awt.Container;
MethodOverload.
java
import javax.swing.*;
public class MethodOverload extends JApplet {
// create GUI and call each square method
public void init()
{
JTextArea outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );
Lines 22-29
Method square
receives an int as an
argument
outputArea.setText( "The square of integer 7 is " + square( 7 ) +
"\nThe square of double 7.5 is " + square( 7.5 ) );
} // end method init
Method square receives an
// square method with int argument
int as an argument
public int square( int intValue )
{
System.out.println( "Called square with int argument: " +
intValue );
return intValue * intValue;
} // end method square with int argument
 2003 Prentice Hall, Inc.
All rights reserved.
26
31
32
33
34
35
36
37
38
39
40
41
// square method with double argument
public double square( double doubleValue )
{
System.out.println( "Called square with double argument: " +
doubleValue );
Outline
MethodOverload.
java
return doubleValue * doubleValue;
} // end method square with double argument
} // end class MethodOverload
Lines 32-39
Overloaded method
square receives a
Overloaded method square
double as an
receives a double as an argument
argument
Called square with int argument: 7
Called square with double argument: 7.5
 2003 Prentice Hall, Inc.
All rights reserved.
27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Outline
// Fig. 6.13: MethodOverload.java
// Overloaded methods with identical signatures.
import javax.swing.JApplet;
MethodOverload.
java
public class MethodOverload extends JApplet {
// declaration of method square with int argument
Lines 8 and 15
public int square( int x )
{
Compiler cannot distinguish betweenCompiler cannot
return x * x;
methods with identical names and distinguish between
}
parameter sets
// second declaration of method square
// with int argument causes syntax error
public double square( int y )
{
return y * y;
}
methods with identical
names and parameter
sets
} // end class MethodOverload
MethodOverload.java:15: square(int) is already defined in MethodOverload
public double square( int y )
^
1 error
Fig. 6.17 Compiler
error messages
generated from
overloaded methods
with identical
parameter lists and
different return types.
 2003 Prentice Hall, Inc.
All rights reserved.
28
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
– factorial (n) = n * factorial (n-1);
 2003 Prentice Hall, Inc. All rights reserved.
29
Final value = 120
5!
5!
5! = 5 * 24 = 120 is returned
5 * 4!
5 * 4!
4! = 4 * 6 = 24 is returned
4 * 3!
4 * 3!
3! = 3 * 2 = 6 is returned
3 * 2!
3 * 2!
2! = 2 * 1 = 2 is returned
2 * 1!
2 * 1!
1 returned
1
1
(a) Sequence of recursive calls.
(b) Values returned from each recursive call.
Fig. 6.14 Recursive evaluation of 5!.
 2003 Prentice Hall, Inc. All rights reserved.
30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Outline
// Fig. 6.15: FactorialTest.java
// Recursive factorial method.
import java.awt.*;
FactorialTest.j
ava
import javax.swing.*;
public class FactorialTest extends JApplet {
JTextArea outputArea;
// create GUI and calculate factorials of 0-10
public void init()
{
outputArea = new JTextArea();
Line 21
Invoke method
factorial
Invoke method factorial
Container container = getContentPane();
container.add( outputArea );
// calculate the factorials of 0 through 10
for ( long counter = 0; counter <= 10; counter++ )
outputArea.append( counter + "! = " +
factorial( counter ) + "\n" );
} // end method init
 2003 Prentice Hall, Inc.
All rights reserved.
31
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// recursive declaration of method factorial
public long factorial( long number )
{
// base case
if ( number <= 1 )
return 1;
Outline
Test for base case
(method factorial
can solve base case)
// recursive step
else
return ( number * factorial( number - 1 ) );
} // end method factorial
} // end class FactorialTest
FactorialTest.j
ava
Lines 29-30
Else return simpler Test
problem
that case
for base
method factorial
might solve
(method
factorial
in next recursive
call
can solve base case)
Line 34
Else return simpler
problem that method
factorial might
solve in next recursive
call
 2003 Prentice Hall, Inc.
All rights reserved.
32
6.14 Recursion vs. Iteration
• Iteration
–
–
–
–
Uses repetition structures (for, while, or do…while)
Repetition through explicit 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
 2003 Prentice Hall, Inc. All rights reserved.
33
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 fewer lines of code
Be careful concerning infinite recursion
 2003 Prentice Hall, Inc. All rights reserved.