Methods
Last modified Sunday, 07-Jul-2024 16:06:39 UTC.
- What are they?
- Methods are named segments of code
- Calling that segment of code (using its name) causes
the segment to be executed before execution continues after the
point of the call.
- A return statement can be used anywhere in a method
to return to the point of call.
The rest of the method is not executed.
- Local variables
(Slides)
- Variables declared in methods are local to that method
- Local variables are recreated each time the method runs
- Local variables are destroyed when the method returns
- Example:
LocalVariables.java
- Transferring data to and from methods
(Slides)
- Passing in data
- The formal parameters defined in the method
header are local variables, and they receive
copies of the actual parameters passed
in the call.
- The values are copied in order, 1st to 1st, 2nd to 2nd, etc.
- Formal and actual parameters need not (but can) have the same
name. It doesn't matter - they're not connected, only the
values of the actual parameters are copied into the formal
parameters.
- Changes to the formal parameters have no effect in the
calling code because they are local!
- Example:
Parameters.java
- Actual parameters need not be variables.
They can be values, calculations, etc.
- Example:
NonVariableParameters.java
- Returning one value
- Methods can call other methods
- What are they good for?
- A program can be written with all the code in the main
method
- Example:
PizzaBoxInMain.java
- In the same way that documents are (should be!) broken into
paragraphs, programs are (should be!) broken into methods.
- Example:
PizzaBox.java
- Modular design
- Recall the process of top-down analysis
- The
bank checkbook example
- This could be written all in the main:
CheckbookInMain.java
(Don't worry about the if else and switch case
stuff - you have not been shown that yet. The point is that it
could be done, but it's one ugly lump of code!)
- The structure chart can be used to guide the development of
code with methods
- The root node is the main method
- Internal nodes are separate methods
- Leaf nodes are code within methods
- Example:
- The design indicates having methods for "Get Information",
"Perform Computation", "Display Results", and "Display
Transaction"
- At this stage you don't have enough tools to make a separate
method for the input (node "Get Information") - you cannot
return more than one value from a method, and that bit has to
get three things.
Patience - we'll get there.
-
CheckbookByDesign.java
- Example: Computing calorie input
- Problem: Compute the number of calories you input each day,
and the number that you should, and show the difference.
- Details: The number of calories you should input is based
on your
Basal Metabolic Rate (BMR), which is your
weight calories plus height calories minus age calories.
The weight calories is 66.0 + (weight in pounds * 6.23).
The height calories is height in inches * 12.7.
The age calories is age in years * 6.8.
The number of calories you should input is based on your BMR
and activity level, using the
Harris Benedict Equation.
On average, it is the BMR multiplied by 1.55.
- Structure chart.
- The design suggests methods for "Input calories", "Regular
meals", "Compute calories", and "Compute required".
- Calories.java
- Methods can be reused, both in a program and in other programs
- Scope
- The scope of a variable is the range of statements in a class
that can use the variable
- Scope works like an onion {{{ }}}
- Local variables are visible from the point of declaration to
the matching closing }
- Parameters are visible from the method's opening { to the
matching closing }
- Class variables are visible throughout the class
- Example:
Parameters.java
- If variables with nested scopes have the same name, references
are to the one with the inner-most scope.
GlobalVariables.java
- Do not use class variables to transfer data between methods.
Seriously, you'll suffer a miserable programmer's death.
And I'll dance on your grave cackling wildly.
GlobalVariables.java
GlobalVariablesRemoved.java
GlobalVariablesFixed.java
- Overloading
- Java allows multiple methods with the same name and return
type, but different formal parameters.
- When such a method is called, the appropriate method is used
dependent on the actual parameters.
- This is called overloading
- Example:
Overloading.java
- Some rules for safe programming with methods
- Make methods private when possible
- Never use class variables to pass data between methods.
- A method over one page/screenfull is too long.
Exercises
- What are methods?
- If a method has seven formal parameters, how many actual parameters
must be provided in a call to that method?
- How many values can a Java method return? Who made that Java design
decision? What should be done to that person?
- Can methods call other methods? Can a method call itself?
- When do formal and actual parameters have to have the same
names?
- What are three reasons for using methods?
Exam Style Questions
- When are local variables in a method created and destroyed?
- What are the formal and actual parameters of a method?
- Write a method that receives a character and integer parameter, and
returns a boolean indicating whether or not the ASCII value of the
character is greater than the integer.
- Explain the relationship between a structure chart and the methods
that may be used in a program.
- What are the scopes of:
- Formal parameters
- Local variables
- final class variables
- What feature allows multiple methods to have the same name?
- How does Java decide which version of an overloaded method to execute?