Modularity: Java Methods - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

Modularity: Java Methods

Description:

Each logical task is implemented by a different module (aka method in Java) ... Java convention: ... The Java compiler determines which method is intended by ... – PowerPoint PPT presentation

Number of Views:84
Avg rating:3.0/5.0
Slides: 27
Provided by: uwo6
Category:

less

Transcript and Presenter's Notes

Title: Modularity: Java Methods


1
ModularityJava Methods
2
Topics to Cover
  • Recall Top-down Design
  • Program Choices
  • Invoking (Calling) a Static Method
  • Defining a Static Method
  • Parameter Passing (Method Communication)
  • A Useful Programming Tool Drawing Diagrams!
  • Method Overloading
  • Method Prototypes

3
Recall Top-down Design
  • A problem can be decomposed into smaller and
    smaller sub-problems until each sub-problem
    represents one logical task
  • Each logical task is implemented by a different
    module (aka method in Java)
  • What do we need to know?
  • How to invoke (aka call) modules (Have we seen an
    example?)
  • How to communicate with modules (Have we seen an
    example?)
  • How to define modules (Have we seen an example?)

4
Recall Top-down Design
  • There are two kinds of Java methods
  • Static methods (aka class methods)
  • Well look at these first
  • Instance methods
  • Well see these later, with objects
  • Lets see some methods in a sample Java program
    Choices

5
/ Choices.java CS026 Lecture Notes Example
Task presents the user with a menu to select
either an average or greatest common divisor
calculation in order to demonstrate static
methods defining, invoking, and parameter
passing/import java.io.public class Choices
public static void main(String args)
throws Exception BufferedReader keyboard
new BufferedReader
(new InputStreamReader(System.in),1)
int choice / user input / do
System.out.println("0. Quit")
System.out.println("1. Average calculation")
System.out.println("2. GCD
calculation") System.out.print("Please
enter your choice ") choice
Integer.parseInt(keyboard.readLine())
if (choice 1) average(keyboard)
else if (choice 2)
euclid(keyboard) else if (choice ! 0)
System.out.println("Invalid choice
try again.") while (choice ! 0)
System.out.println() System.out.println("
program Choices terminates!")
6
public static void average(BufferedReader
keyboard) throws Exception int
howmany0 / number of values to be
averaged / int sum0 / running
sum / int aNumber / user input
/ do System.out.print("Please
enter a number (0 to finish) ")
aNumber Integer.parseInt(keyboard.readLine())
sum sum aNumber howmany
while (aNumber !0)
System.out.println() System.out.println("Th
e average of the numbers is "
(float) sum / (howmany-1))
7
public static void euclid(BufferedReader
keyboard) throws Exception int biggest,
smallest / user input /
System.out.print("Please enter an integer ")
biggest Integer.parseInt(keyboard.readLine()
) System.out.print("Please enter another
integer ") smallest Integer.parseInt(ke
yboard.readLine()) if (smallest
biggest) int temp smallest
smallest biggest biggest
temp euclidAlgorithm(smallest,
biggest) public static void
euclidAlgorithm(int small, int big)
System.out.print("The greatest common divisor of
" big " and "
small " is ") int remainder /
remainder from integer division / do
remainder big small if
(remainder ! 0) big small
small remainder
while (remainder ! 0)
System.out.println(small)
8
Program Choices
Screenshot of BlueJ Running the Program Choices
9
Program Choices
  • Discussion Points
  • Run the program and be sure to observe the
    changes in behaviour
  • Of the average algorithm
  • Of Euclids algorithm
  • What are the modules (methods)?
  • Java convention method identifiers (i.e. names)
    begin with lower case and use capitals to
    indicate word boundaries e.g. euclidAlgorithm

10
Invoking a Static Method
  • Method name followed by parentheses
  • Parentheses contain actual parametersvalues
    (variables or constants) required by the method
  • Example of actual parameters?
  • The number and types of actual parameters must be
    the same as the number and types of the formal
    parameters in the method definition
  • Examples of formal parameters?
  • What happens when a method is invoked?

11
Method Invocation control is given to
the method each formal parameter is given
(assigned) the value of its
corresponding actual parameter
statements in the method body are executed
until (either a return statement) OR
(the end of the method body)
is encountered the method returns
i.e. control is given back to the
environment following the invocation
(call)
12
Defining a Static Method
  • General Form public static
    (parameters)
  • public is an access modifier which allows other
    modules to be able to use this method
  • Later, well see another access modifier private
  • static indicates that the method is a class
    method it is not associated with an object

13
Defining a Static Method
  • Method body contains
  • Local variable declarations variables used while
    the method is executing
  • Said to be within the methods scope they only
    exist (i.e. have space reserved for them in main
    memory) while the method is executing
  • Scope of an identifier the set of statements
    (aka block) that can access the identifier
  • Statements to be executed when the method is
    called

14
Parameter Passing (Method Communication)
  • Parameters are passed by value that is, only the
    values are given to the method not their
    locations in memory. What does this imply?
  • Thus
  • Methods can return a value return type the
    type of the value returned by the method via a
    return statement the keyword void is used if no
    value is returned
  • An example?
  • Who determines if a method returns a value or not?

15
A Useful Programming Tool Drawing Diagrams!
  • What happens in main memory with method
    definition, invocation, and communication?
  • Being able to draw a diagram representing main
    memory at various stages in the execution of a
    program is very helpful
  • In understanding the mechanisms involved in
    method definition, invocation, communication
  • In debugging
  • Example Program Choices

16
More on Program Choices
  • Things to note
  • Observe the algorithm modifications
  • to the average algorithm
  • to Euclids algorithm
  • Increment operator howmany is the same
    ashowmany howmany 1(yes, there is a
    decrement operator -- )
  • throws exception error handling required when
    a method involves input

17
More on Program Choices
  • Useful things to do
  • Identify method definitions, method invocations,
    local variables, formal parameters, actual
    parameters
  • Modify the program so that one of the methods
    returns a value (an int, a double, a boolean)
  • Identify the scope of local variables, actual
    parameters, formal parameters, constants

18
More on Program Choices
  • Other useful things to do
  • Create syntax errors! For example
  • Remove a throws exception
  • Misspell an identifier
  • Remove a keyword
  • Use a keyword as a variable name
  • Change the order of the actual parameters
  • Remove an actual parameter
  • Add an actual parameter,
  • Create run time errors! (Examples?)

19
Method Overloading
  • Allowing different versions of methods with the
    same name to exist in the same class
  • The Java compiler determines which method is
    intended by examining the parameters with respect
    to
  • The number
  • The type
  • Consider Program OverloadingDemo

20
/ OverloadingDemo.java CS026 Lecture Notes
Example Task demonstrate method overloading
/import java.io.public class
OverloadingDemo public static void
main(String args) throws Exception
BufferedReader keyboard new BufferedReader
(new InputStreamReader(Sy
stem.in),1) int i,j / user input
/ double x,y / user input / /
demonstrate the integer version of min /
System.out.print("Enter an integer ") i
Integer.parseInt(keyboard.readLine())
System.out.print("Enter another integer ")
j Integer.parseInt(keyboard.readLine())
System.out.println("The minimum value of " i
" and " j " is "
min(i,j)) System.out.println()
/ demonstrate the double version of min /
System.out.print("Enter a real ") x
Double.parseDouble(keyboard.readLine())
System.out.print("Enter another real ")
y Double.parseDouble(keyboard.readLine())
System.out.println("The minimum value of " x
" and " y " is "
min(x,y)) System.out.println()
System.out.println("The minimum value of " i
" and " x " is "
min(i,x))
21
public static int min(int num1, int num2)
System.out.println("int version of min
invoked") if (num1 else return num2 public static
double min(double num1, double num2)
System.out.println("double version of min
invoked") if (num1 else return num2 / this won't
compile more than just the return type
needs to be different! why? public static
void min(int num1, int num2)
System.out.println("void version with 2
parameters invoked") /
22
OverloadingDemo Program
Screenshot of BlueJ Running the OverloadingDemo
Program
23
OverloadingDemo Program
  • Discussion Points
  • Parameters determine which version is to be
    invoked
  • Which type conversions are automatically
    performed?
  • What role does the return type play?
  • What is the advantage of overloading?

24
Method Prototypes
  • We know
  • Methods have zero or more parameters Examples?
  • Methods either return a value or not
    (void)Examples?
  • The prototype for a method gives the information
    about its parameters and its return value
  • Example
  • Given a prototype, one can invoke the method
    without knowing the details of how the method is
    implemented

public static double min(double num1, double
num2) / returns the smaller of the two
parameters /
25
The Java API
  • The Java API (Application Programming Interface)
    on the Sun web site gives prototypes of
    predefined methods
  • See the link on the CS 026 web page
  • Were going to see and use a predefined class
    next

26
Further Reading
  • The following sections from the Java 5.0 Program
    Design text supplement these notes nicely
  • 7.1, 7.2, 7.5 Omit Listing 7.5 (and discussions
    thereof)
Write a Comment
User Comments (0)
About PowerShow.com