Next: Examples of definitions of
Up: Unit 03
Previous: Methods seen as modules
In Java, the simplest forms of methods are the static methods.
Static methods are methods (defined in a class) that do not have an
invocation object.
Definition of a static method
Syntax:
header block
- header is the header of the static method and has the
following form:
public static resultType methodName(formalParameters)
where
- public indicates that the method being defined is accessible
from the outside the class (see later)
- static indicates that the method is static (i.e., it has no
invocation object)
- resultType is the type of the result returned by the
method, or void, if the method does not return any result
- methodName is the name of the method
- formalParameters is a list of parameter declarations
(type and name) separated by commas; each parameter is a variable; the
list of parameters may also be empty
- block is the body of the method containing the
statements that will be executed when the method is being called; it has
the form:
{
statements
}
Semantics:
Defines a static method by specifying its header and body.
- The header indicates:
- the name of the method,
- the number and type of its formal parameters,
- the type of the returned value, if any, and
- the accessibility of the method from outside the class where it is
defined.
- The body of the method specifies the statements that have to be
executed when the method is called.
- The formal parameters are used to pass objects, or more generally
information, which is used in the body of the method. The formal
parameters are used inside the body of the method in the same way as
initialized variables (the initialization is done at the moment the method
is called, by assigning to each formal parameter the value of the
corresponding actual parameters - see later).
- The returned result, if any, is the value of the method-call. If the
method does not return any result, then it must not be used to compute a
result but to perform side effect on the objects denoted by the formal
parameters.
Example:
The static method main, used before. Such a method has always the
form:
public static void main (String[] args) {
...
}
The header of the main method shows that:
- it is a method accessible from outside the class where it is defined
(public),
- it is a static method (static),
- it does not return any result (return type is void), and
- it has a parameter of type array of strings (see Unit 7). Up-to now, in
our programs, we have never used this parameter.
Note: The definition of a method does not cause its activation.
Next: Examples of definitions of
Up: Unit 03
Previous: Methods seen as modules