Methods

advertisement
Methods
BCIS 3680 Enterprise Programming
Typographical Conventions
Syntax rules are shown in red, mono-spaced font.
Code examples (partial or complete Java/JSP statements)
are shown in blue mono-spaced font.
Key terms are shown in purple, boldfaced font.
Items in [square brackets] are optional.
Items in <angled brackets> are placeholders; they
need to be replaced with meaningful values in real code.
Items displayed as { item1 | item2 | item3 } are
mutually exclusive options. One and only one item is required
and it must come from the the listed items.
Minor deviations may occur occasionally.







2
Overview
Why methods
Two types of methods
Defining a method
Calling a method






Passing arguments
Passing by value/reference
Method overloading
Pay particular attention to the three Summary slides!


3
Why Methods?
Benefit #1: Reusability.


Methods simplify programs. If a specific task is performed in several
places in the program, a chunk of code (method) to perform that task
can be written once, and then be executed anytime it is needed.
Benefit #2: Easy maintenance



4
Methods are commonly used to break a problem down into small
manageable pieces. This is called divide and conquer.
Future modification of code will be easier because only a small piece
of the entire program is affected each time.
Calling a Method
If Method A takes a detour
and invokes Method B,
Method A is said to “call
Method B”, “make a method
call to B”, etc.
Once the action is done or a
value is returned from
Method B, Method A will
move on to the statement
right after the method call.


5
Method A
Method B
Two Types of Methods
void Method


One that simply performs a task and then terminates.
System.out.println("Hi!");
Value-Returning Method


Not only performs a task, but also sends a value back to the code that
called it.
int number = Integer.parseInt("700");
return number;
6
Method Header
The calling method needs a few pieces of information to call a
method correctly:




What method is being call? – method name
Is that a void or value-returning method? – return type
Do I need to provide input to the called method for it to work on? –
parameter list
These are defined in the method header.


Plus, the method header also includes the access modifier.
A method signature is part of the header.

7
Defining a Method
8
What Is in a Parameter?
Parameters are input expected from the calling method.
A method must tell the world:



What kinds of input values, if any, it expects (parameters)
and

The exact order of the parameters
The parameters are “placeholder” variables in the method so
that statements can be written to specify how input from the
calling method should be handled.

9
Parameter List


Pairs of dataType varName separated by commas.
The parameter list specifies:

Parameter name




Descriptive names are helpful. But they are for reference only. The calling
method does not have to match these names in its code.
The data type of each parameter
The order of the parameters
Parameters are optional. There are times when none are
needed. In that case, use a blank pair of parentheses.
10
Summary #1: Writing Method Headers



It is the line above anything else in the method (namely, it
appears before the opening curly brace for the method).
For ordinary methods, there is no semicolon after the closing
parenthesis for the parameter list.
For each parameter, two items are needed –



Data type
Parameter name
DATA TYPE MUST PRECEED A PARAMETER NAME.
11
Parameter, Here Is Argument…

An “argument” refers to the same thing (input from the calling
method) from the calling method’s perspective.


The term is “parameter” from the called method’s perspective.
When the calling method passes arguments into the called
method, it must make sure that:


12
Each of the argument is of the same data type as that of its
corresponding parameter.
The arguments are passed into the method in exactly the same order
as that of their corresponding parameters.
Passing Arguments

Include only variable names/expressions in your argument
list.


Including data type keywords in your argument list will cause a
compiler error.
Even if the method takes no arguments, the parentheses are still
required.
13
Passing Arguments
The argument 50 is copied into the num1
parameter.
The argument 10.25 is copied into the
num2 parameter.
getTotal(50, 10.25);
public void getTotal(int num1, double num2)
{
double total;
//to hold the sum
total = num1 * num2;
System.out.println("The total is " + total);
}
14
Calling a Method
15
Summary #2: Calling A Method

When you write a statement to call a method, take note of these:





16
This statement is part of the method in which it belongs. In other
words, it appears somewhere between the opening and closing curly
braces that enclose the method body.
A semicolon is needed to indicate the end of the statement.
Even if the called method does not expect input from this method, you
still must include an empty pair of parentheses before the semicolon.
If the called method expects input (has parameters), you must provide
argument(s). You may pass them as literals, expressions, variables, or
a mixture of them. If you pass variable names as arguments, make
sure you have defined them already.
NO DATA TYPE IS NECESSARY BEFORE THE ARGUMENT
NAMES!
Returned Values

If a method returns a value to the caller, the caller must either:

Use a container (a variable) to hold the value, e.g.,
avgPrice = calcAveragePrice();

Or make it part of an expression, e.g.,
total = calcAveragePrice() * quantity;


When either of the above two statements is run, the value returned
from method replaces the calcAveragePrice() part and is
further processed.
In contrast, if a called method does not return a value, no new
variable is needed and the method call is a statement by itself.
crunchNumbers();
printInvoices();
17
Summary #3: Managing Return Values

When calling a void method –



Simply write the called method’s name, followed by a parenthesized
list of arguments (in the form of variable names, expressions, or
literals, but no data types) or empty parentheses (if applicable), then
by a semicolon.
This is all you need.
When calling a value-returning method –



18
What worked above for calling a void method is not enough, namely,
what you wrote above cannot stand by itself.
It must be part of a longer statement (see previous slide).
Usually it is part of an assignment statement or expression.
Primitive Types Are Passed by Value



In Java, all arguments of the primitive data types are
passed by value, which means that only a copy of an
argument’s value is passed into a parameter variable.
A method’s parameter variables are separate and distinct
from the arguments that are listed inside the parentheses of
a method call.
If a parameter variable is changed inside a method, it has
no affect on the original argument.
19
What About Reference Types (Objects)


They appear to be passed by reference. But in fact they are not.
Just remember, primitive or reference types, the impact of the
method call on the variables in the calling method is the same –
they just don’t get changed by the method call.




For primitive types, the method makes a copy of the primitive value
and works with the copy.
For reference types, the method makes a copy of the value stored in
the object, saves the copy into a new memory location (another
reference), and works with that memory location.
In both cases, Java does not want to touch the argument variable. It
has to go extra miles for reference types because the way values are
stored in them is more complex than primitive types.
For an example, see my annotated PassByRef.java file.
20
Local Variables




A local variable is declared inside a method and is not
accessible to statements outside the method.
Different methods can have local variables with the same
names because the methods cannot see each other’s local
variables.
A method’s local variables exist only while the method is
executing. When the method ends, the local variables and
parameter variables are destroyed and any values stored
therein are lost.
Local variables are not automatically initialized with a
default value and must be given a value before they can be
used.
21
Method Signature

Method Signature = Method Name + Parameter List


Note the access modifier and return data type are not part of the
method signature.
Method Header = Access Modifier + Return Type + Signature
22
Method Overloading

When two or more methods have the same name but different
parameter lists, the methods are overloaded.


In other words, their method signatures are different.
It provides two or more versions of a method that work with:



23
Different number of parameters;
Same number of parameters with different data types;
Or both.
Method Overloading
24
Using an Overloaded Method

Suppose Method A is overloaded. Method B calls A by passing
to A a set of arguments. The version of A that is executed is the
one whose parameter list matches the arguments passed in by
B in terms of:



25
The number of arguments,
The data type of the arguments, and
The order of the arguments.
Download