An Object-Oriented Approach to Programming Logic and

Download Report

Transcript An Object-Oriented Approach to Programming Logic and

An Object-Oriented Approach to
Programming Logic and Design
Fourth Edition
Chapter 6
Using Methods
Objectives
In this chapter, you will learn about:
• The advantages of modularization
• Modularizing a program
• Declaring local and global variables and constants
• Methods that require parameters
• Methods that return a value
• Passing an array to a method
• Overloading methods
• Using predefined methods
An Object-Oriented Approach to Programming Logic and Design
2
Understanding the Advantages of
Modularization
• Modules
– Smaller part of a larger task
– Also called methods, subroutines, functions, or procedures
• Advantages of modularization
–
–
–
–
Provides abstraction
Simplifies the logic
Allows multiple programmers to work on a problem
Allows you to reuse work more easily
An Object-Oriented Approach to Programming Logic and Design
3
Modularization Provides
Abstraction
• Abstraction
– Process of focusing on important properties while ignoring
small details
– Example: “do laundry” is an abstract task; it doesn’t list the
small details like “pick up laundry basket,” etc.
• All computer programs provide some level of
abstraction
– No longer need to understand low-level computer circuitry
instructions to write a computer program
• Methods provide a way to achieve abstraction
An Object-Oriented Approach to Programming Logic and Design
4
Modularization Simplifies the Logic
• With modularization:
– Individual methods are smaller and easier to follow
– Errors are easier to find
• Methods
– Execute a single, finite task
– Smaller methods are less complex and therefore more
reliable
An Object-Oriented Approach to Programming Logic and Design
5
Multiple Programmers Can Work
on a Problem
• Modularization
– Allows division of work among programmers
– Speeds up development process
• Used in the development of commercial software
applications
An Object-Oriented Approach to Programming Logic and Design
6
Modularization Allows You to
Reuse Your Work
• Methods
– Can be used more than once within a program
– Can be reused to other programs
• Reusability
– Feature of modular programs that allow methods to be
reused
• Reliability
– Feature of modular programs that indicates methods have
been tested and proved to function correctly
An Object-Oriented Approach to Programming Logic and Design
7
Modularizing a Program
• Application classes contain a main() method
– May include other methods that main() can use
• Parts of a method
– Header: contains method identifier and other information
– Body: contains all statements in the method
– Return statement: marks the end of the method
• To use a method, call the method using its name
• Flowchart conventions
– Method call symbol: a rectangle with a bar across the top
– Method name goes in the rectangle
An Object-Oriented Approach to Programming Logic and Design
8
• Figure 6-1
– Accepts customer
name and balance
due and produces a
bill
– Only uses main()
method
Figure 6-1
An Object-Oriented Approach to Programming Logic and Design
9
• Figure 6-2
– Shows modularized
version of customer
billing example
– main() method calls
displayAddressInfo()
method
– Method is reusable
– main() method is
easy to follow
Figure 6-2
An Object-Oriented Approach to Programming Logic and Design
10
Modularizing a Program (cont’d)
• displayAddressInfo() method
– Full name: BillingProgram.displayAddressInfo()
– Only use full name when called in another class
• Statements contained in a method are said to be
encapsulated
• Breaking a program into methods
– Requires experience; no specific rules to follow
• Functional cohesion
– Refers to the extent to which a method’s statements are
focused on the single, specific method task
An Object-Oriented Approach to Programming Logic and Design
11
Declaring Variables and Constants
within Methods
• Any statements can be included in methods
–
–
–
–
Input
Processing
Output
Variable and constant declarations
• Variables and constants declared within a method
–
–
–
–
Usable only within the method
Considered local, in-scope, or visible
Go out-of-scope (cease to exist) when method ends
Figure 6-3 on next slide shows declarations with a method
An Object-Oriented Approach to Programming Logic and Design
12
• Figure 6-3
– Three named
constants are
declared within
the method
Figure 6-3
An Object-Oriented Approach to Programming Logic and Design
13
Declaring Variables and Constants
within Methods (cont’d)
• Variables and constants declared within main()
– Local to main: Cannot be used in method
• Global variables
– Accessible to the entire class
• When methods must share data
– Pass data into and return data from method
• When calling a method, you must know:
– Name of the method
– What type of information to send to the method, if any
– What type of return data to expect from the method
An Object-Oriented Approach to Programming Logic and Design
14
Creating Methods that Require
Parameters
• Argument
– Data item passed into a method from a calling program
• Parameter
– Method receives the argument into a parameter
• Argument and Parameter
– Closely related terms
– Calling method sends an argument to a called method
– Called method accepts the value as its parameter
An Object-Oriented Approach to Programming Logic and Design
15
Creating Methods that Require
Parameters (cont’d)
• Example: Modify displayAddressInfo()
method to display a message preceding the name
and address on the bill if the balance is over $1000
• Four approaches to modifying the method
– Rewrite the program to eliminate the
displayAddressInfo() method and place all
statements within main()
– Retain the displayAddressInfo() method but make
the balance variable global by declaring it outside any
methods
An Object-Oriented Approach to Programming Logic and Design
16
Creating Methods that Require
a Single Parameter (cont’d)
• Four approaches to modifying the method (cont’d)
– Retain the displayAddressInfo() method, add a
local variable to displayAddressInfo(), and
prompt the user for the balance again within the method
– Store the variable that holds the balance in main() so it
can be used to display the customer’s balance and pass the
balance to the displayAddressInfo() method
• Best choice: see Figure 6-4 on the next slide
An Object-Oriented Approach to Programming Logic and Design
17
• Figure 6-4
– Billing application
that passes an
argument to a
method
Figure 6-4
An Object-Oriented Approach to Programming Logic and Design
18
Creating Methods that Require
a Single Parameter (cont’d)
• Figure 6-5
– Shows sample output from billing application in Figure 6-4
– Prompts are added for customer data
– Program is executed in a command-line environment
Figure 6-5
An Object-Oriented Approach to Programming Logic and Design
19
Creating Methods that Require
a Single Parameter (cont’d)
• Method that can receive a parameter must include
the following information in header’s parentheses
– Type of parameter
– Local name for the parameter
An Object-Oriented Approach to Programming Logic and Design
20
Passing Arguments by Value
and by Reference
• Two ways to pass an argument into a method
– Passed by value
• Copy of value is sent to the method
• Stored in a new memory location
– Passed by reference
• Address of original variable is sent to the method
• A variable in the calling method can have the same
identifier as the parameter in the method header
– Passed variable: a temporary placeholder
– Parameter is re-declared with each method execution
An Object-Oriented Approach to Programming Logic and Design
21
Figure 6-6
• Figure 6-6
– Argument is
passed by value
• Figure 6-7
– Shows sample
output
Figure 6-7
An Object-Oriented Approach to Programming Logic and Design
22
Passing Arguments by Value
and by Reference (cont’d)
• Implementation hiding
– Calling a method without understanding the details of how
the method works
• Method’s parameter list
– parameter types within parentheses in a method header
• Method’s signature
– the method’s name and parameter list
• Calling method needs to know:
– Method’s signature
– What type of return data to expect
An Object-Oriented Approach to Programming Logic and Design
23
Passing Arguments by Value
and by Reference (cont’d)
• Passing by reference
– Gives receiving method address of original variable
– Procedure differs by programming language
– Usually involves placing a special symbol or keyword in the
method header’s parentheses
– Implementation hiding is reduced
An Object-Oriented Approach to Programming Logic and Design
24
Creating Methods That Require
Multiple Parameters
• To create and use methods with multiple parameters
by:
– List arguments in method call separated by commas
– List a data type and local identifier for each parameter in
header’s parentheses separated by commas
– Pass arguments in correct order
– Figure 6-8 on the next slide shows a method that accepts
two parameters
An Object-Oriented Approach to Programming Logic and Design
25
• Figure 6-8
– Program calls
computeTax()
method that
requires two
parameters
Figure 6-8
An Object-Oriented Approach to Programming Logic and Design
26
Creating Methods That Return
a Value
• Variable declared within a method ceases to exist
when method ends
• To retain a value, return the value to the calling
method
– Return type must match data type of value that is returned
– Return types can be any data type
• Return Type
– The data type of the value that the method sends back to
the location where the call is made
• Method could also return nothing - a void method
An Object-Oriented Approach to Programming Logic and Design
27
• Figure 6-9
– Payroll program calls a method that
returns a value
– Return type num
precedes method
name in header of
getHoursWorked()
– Numeric value is
included in return
statement
Figure 6-9
An Object-Oriented Approach to Programming Logic and Design
28
Figure 6-9
• Figure 6-9
– Pseudocode for Payroll program
– Calls the method getHoursWorked()which returns a
value that is stored in the variable hours
An Object-Oriented Approach to Programming Logic and Design
29
• Figure 6-10
– Sample of a program
that uses a method’s
return value without
storing it
Figure 6-10
An Object-Oriented Approach to Programming Logic and Design
30
Creating Methods That Return a
Value (cont’d)
• Methods can include multiple return statements
– Practice is not
recommended
– Every selection structure
has one entry point and
one exit point; multiple
return statements violate
this convention
– Example: Figure 6-11
Figure 6-11
An Object-Oriented Approach to Programming Logic and Design
31
• Figure 6-12
– Shows best solution to
returning one of several
values
Figure 6-12
An Object-Oriented Approach to Programming Logic and Design
32
Passing an Array to a Method
• Pass single array element to a method
– Same manner as passing a variable or constant
• Pass entire array to a method
– Use square brackets to indicate that method parameter is
an array
– Passed by reference
– Changes made to the array within the method are
permanent
An Object-Oriented Approach to Programming Logic and Design
33
• Figure 6-13
– Array of four
numeric values
is created
– Array is sent to
methods three
times
Figure 6-13
An Object-Oriented Approach to Programming Logic and Design
34
• Figure 6-13
– Pseudocode for
PassEntireArray
program
Figure 6-14
• Figure 6-14
Figure 6-13
An Object-Oriented Approach to Programming Logic and Design
– Output for
PassEntireArray
program
35
Overloading Methods
• Overloading
– Allows for diverse meanings for a single identifier
• Overloaded methods
– Multiple methods with the same name but different
parameter lists
– Have different signatures
• Polymorphism
– Ability of a method to act appropriately according to the
context
– Example of polymorphism: overloaded methods
An Object-Oriented Approach to Programming Logic and Design
36
• Figure 6-15
– Two overloaded versions of
the printBill() method
– Array is sent to methods
three times
An Object-Oriented Approach to Programming Logic and Design
Figure 6-15
37
• Figure 6-16
– Two additional overloaded
versions of the method
printBill()
An Object-Oriented Approach to Programming Logic and Design
Figure 6-16
38
Avoiding Ambiguous Methods
• Ambiguous methods
– Situation in which compiler cannot determine which
method to use
– Can occur with an overloaded method
– Compiler decides which version of a method to use based
on parameter data type
– Methods with identical names, identical parameter lists
and different return types are ambiguous
• Avoiding ambiguous methods
– Provide different parameter lists for methods with same
name
An Object-Oriented Approach to Programming Logic and Design
39
• Figure 6-17
– Two versions of method
printBill()
– One version accepts
customer balance and
discount rate
– Other version accepts
customer balance and
discount amount
– Both versions require
same data type
Figure 6-17
An Object-Oriented Approach to Programming Logic and Design
40
• Figure 6-17
– Pseudocode for program
that contains ambiguous
method call
– Contains two versions of
method printBill()
Figure 6-17
An Object-Oriented Approach to Programming Logic and Design
41
Using Predefined Methods
• All modern programming languages contain
predefined methods
• May originate from various sources
– Built into a language
– Created by other programmers on a team
– Standard method written for a company
• Examples
– Printing message on the screen
– Mathematical methods such as taking square root
– Selecting a random number
An Object-Oriented Approach to Programming Logic and Design
42
Using Predefined Methods (cont’d)
• Methods written as a convenience
– Already written, tested, and available
• Information needed when using predefined methods
– Method’s name
– The method’s required parameters
• Might be multiple overloaded versions
– Method’s return type
• Do not need to know how method is implemented
An Object-Oriented Approach to Programming Logic and Design
43
Summary
• Modularization
–
–
–
–
–
Process of converting a larger task into smaller methods
Provides abstraction
Simplifies logic
Makes dividing work among programmers easier
Allows reuse of methods
• When creating a method, include a header, a body,
and a return statement
• To use a method, call the method by using the
method’s name
An Object-Oriented Approach to Programming Logic and Design
44
Summary (cont’d)
• Variables and constants declared in a method are
local to the method
• When you pass data into a method, it is called an
argument to the method
• When the method receives the data item, it is stored
in a parameter
• Two ways of passing data: by value and by reference
An Object-Oriented Approach to Programming Logic and Design
45
Summary (cont’d)
• Return type
–
–
–
–
Indicates the data type of the value that will be returned
Also known as the method’s type
Indicated in front of method name when method is defined
Method returns a value using a return type
• Arrays
– Can pass single array element to a method
• Exact same manner variable or constant
– Can pass an entire array
– Always passed by reference
An Object-Oriented Approach to Programming Logic and Design
46
Summary (cont’d)
• Overload a method
– Write multiple methods
• Shared name, different parameter lists
• Compiler understands meaning based on arguments
– Risk of creating ambiguous methods
• Compiler cannot determine method to use
• Predefined methods
– Built into programming language
– Saves programming time and effort
An Object-Oriented Approach to Programming Logic and Design
47