Table of Contents
- Introduction to methods
- Paremeters / arguments
- How call works
- Defining a static method
- Example with 3 methods
1. Introduction to methods
Basic idea - A named group of statements - Verbs
Java statements are grouped together into units called methods.
Each method must be inside a class. It has a name, which starts with
a lowercase character and typically is a verb because it
does something.
Terminology: Call / return
When you go to a method, the term is call. When the group of statements
in the method is finished, the method returns to the where it was
called from.
1.2. Static / class methods
1.2.1 main method
This tutorial starts with static (also called class) methods
because all applications start with the static method main.
Altho main is static, as you progress in Java, you will find that
relatively few of your methods will be static - only those that
are self-contained, depending only on parameters.
This self-contained nature makes them a good place to start the
discussion of methods.
1.2.2 Method calls occur before parentheses ()
You can always identify a method call because it it followed by left and
right parentheses, which may contain arguments (parameters).
If you see a left parenthesis with a name preceding it, it will be a method
call, or a constructor, which is very similar.
Here is an example where the method names are hilited.
|
|
The above code defines the main method, which someone
(eg, the operating system) will call.
To do its work, main calls on other methods:showInputDialog which is defined in the JOptionPane class), parseDouble which is defined in the Double class, and showMessageDialog which is also in the JOptionPane class.
When you call a static method in someone else's class, you have to
precede it with the name of the class containing its definition, followed by a dot.
Static and Instance Method calls - Preceded by class or value
The calls for static and instance methods look the same, except
that a static method name is preceded by the class name (unless it's in the
same class when the class name can be omitted).
Instance method calls are preceded by a value instead of a class name.
Business analogy - different departments
You could think of methods as being similat to departments /sections / groups
in an organization, which are responisible for doing one thing.
2. Parameters / Arguments
Method call arguments (actual parameters) - enclosed in the parentheses
When you call a method, you can pass information for it to use.
These arguments (also called actual parameters) are inside
parentheses following the method name. Use commas to separate
the arguments if there is more than one. The previous program is
shown below, but the arguments in the calls (not the main definition)
are hilited.
|
|
3. How call works
How to define your own method
The previous program is rewritten below to define a method to
convert from kilometers to miles.
The method call, and the first line of the method definition are hilited.
|
|
The method call process
Terminology - call and return
A call is the process of suspending one method (the caller) in the middle in
order to start another method (the called method). When the called method
is finished, it returns to the point immediately after the call took
place. Commonly this is described as the returning to the place of the
call, but of course it is really the next instruction or we would have a loop.
Terminology - argument and parameter
Terminology regarding method parameters/arguments is inconsistent, but
the most common practice is the following.
Argument is the name for each of the comma-separated values in
a method call. However, these are sometimes referred to as
actual parameters or simply parameters.
The preferred usage is argument.
Parameter is the name for each of "variable" in the method
definition that corresponds to the argument in the call.
The term formal parameter is sometimes used.
Specific example
We'll take a look at how the convertKmToMi method is called,
because it illustrates how all methods are called. Later, when we look
at instance methods, the only difference will be the automatic addition
of one extra parameter.
Assume we've gotten to the call on line 22.
mi = convertKmToMi(km);
Before the assignment can be made, the right-hand-side must be evaluated.
In this case, the method must be called. The following describes the steps
in calling a method.
1. Evaluating the arguments
The only argument in this call, kilometers, is a simple
variable that doesn't require evaluation. When an expression is used
as an argument (eg, in line 25), the expression must be evaluated before
the call can be made.
2. Creating a new Stack Frame
When a method is called, memory is required to store the following information.
- Parameter and local variable storage. The storage that is needed for
each of the parameters and local variables is reserved in the stack frame.
In theconvertKmToMimethod's stack frame there
would be space for the parameterkilometersand
the local variablemiles.
Themainmethod's stack frame has the one parameter
argsand three local variables,
kmStr,km, andmi.
- The saved state of the calling method. You don't have to worry about
this; it's automatically saved for you.
It includes the calling method's return address,
which is where to continue when it's time to return.
- Other working storage needed by the method may be required. You don't have
to do anything about this because it's handled automatically.
3. Initializing the parameters
When the arguments are evaluated, they are assigned to the
local parameters in the called method. In the example
above, the value in km in main is assigned to
the parameter kilometers in convertKmToMi.
4. Executing the method
After the stack frame has been initialized, execution starts with the
first statement and continues as normal.
5. Returning from the method
When a return statement is encountered, or the end of a void method
is reached, the method returns.
For non-void methods, the return value is passed back to the calling method.
The stack frame storage for the called method is made available for reuse
by other methods.
Execution is continued in the called method immediately after where
the call took place.
Defining a static method
How to define your own method
The previous program is rewritten below to define a method to
convert from kilometers to miles.
The method call, and the first line of the method definition are hilited.
|
|
Anatomy of the convertKmToMi method
There are several parts to a method
- Visibility -
public,private, or package -
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}
When you define a method, you should think about who can use it.
To achieve the best encapsulation (information hiding) you should
always declare methods with the least visibility that works.
Here are the four options, from least visible to most visible.private- If you don't want any other class to use it,
declare it private. This is a good choice.- None (package) - If you don't specify anything, the default visibility allows
only classes in the same package (directory) to
see it. This is a common choice.
protected- Don't use this controversial option which limits
visibility to child classes.public- Let's anyone see it. Choose this if you've defined
a method that will be used by others outside of your project.
Note thatmainmust be
declaredpublicso the run-time system
can call it.
- Class (static) or instance method
-
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}A method that doesn't use variables other than parameters should be declared
static. If thestatickeyword is omitted, the
method will be an instance method. This example uses static,
but if it's in a class that represents an object, you will usually define instance methods.
- Return type
-
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
} - Method name
-
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}Method names should begin with a lowercase letter. Method names are typically
verbs, whereas variable names are usually nouns. - Parameter(s)
-
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}In parentheses following the method name are the parameters (sometimes called formal parameters). There is only
one parameter in this example -kilometers.
The type of each parameter must be specified before the name (eg,double).
The parameters are variables that only exist inside the method, and they are
assigned values from the arguments (actual parameters) when the method is called. - Method body
-
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}The body of a method is the statements which are executed when the method is called
are enclosed in braces following the the method header.
Additional local variables may be defined (eg,miles). - Return statement
-
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}A method returns to the caller after it has done what it wants.
If the method returns a value (not a void method), it must contain
areturnstatement that specifies a value to return.
This example returns the value in miles.
The return statement can be followed by an expression of the appropriate type, not just
a single value. For example, this method body could be replaced
by a single return statement.
private static double convertKmToMi(double kilometers) {
return kilometers * 0.621;
}
Example with three methods
Here is another variation of the program, this time using three methods.
Altho there is no real need for these methods in
such a small program, large programs are in fact composed of many small methods.
It is the essential way that all code is structured.
There are a couple of things worth noting in this example.
Each of the user-defined method names is hilited.
- One of the methods is void, so it doesn't return a value.
- To of the methods call other methods.
- The main program consists of calls to other methods.
Source code
|
|