Defining Methods that Accept Parameters

Purpose:

To allow a method to receive information from the calling instance.

Mechanics:

<modifiers> <return type> <method name>(<paramter list>) {
/* statements */
}

where <parameter list> has the following structure:

<parameter type1> <formal parameter name1>,
<parameter type2> <formal parameter name2>,
<parameter typeN> <formal parameter nameN>

Example:

public void drawCircle(int radius) {
/* statements */
}

Usage:

  • <method name> is any valid identifier which is unique to the class. It names a block of statements which, when executed in order, define a behavior for the class.
  • The declarations of parameters are similar to declarations of instance and local variables without motifiers: a class name or base type is followed by a valid identifier. Commas are used to separate the declarations of parameters. The last parameter is an exception; a right parenthesis is placed before the bracket (or semicolon if the method is abstract).
  • Within the method definition, Java treats parameters as if they were local or instance variables.
  • There need not be a parameter list for every method declaration. If the method takes no parameters, <method name> is simply followed by ().

Restrictions:

If <formal parameter name i> is the same identifier as an instance variable of the class which contains <method name>, then Java will assume that a reference to that identifier is a reference to the parameter, not the instance variable. A statement can refer to the instance variable by refering to this.<identifier>.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu