|
The Department of Computer Science & Engineering
|
CSE 115
Introduction To Computer Science for Majors I
Lecture C
Lecture Notes
Stuart C. Shapiro
Spring, 2001
Methods and Parameters
- Reading
- Brown U. Notes, Chapter 3
- Barnes, Chapters 3, 4
- Variables
- Variables include static (or class) variables, instance
variables, local (or method) variables, and formal parameters.
- A variable has a name, a type, and a value.
- The compiler will check that the value given to a variable is
compatible with the variable's declared type.
Java-speak uses the terms "message" and "method" to refer to the
same thing---a capability or behavior of an object.
Can say one object sends a message to another, which the latter
understands, or that one object calls another's method.
Define a method, specifying its list of formal parameters (or
arguments), with their types.
Call a method with one actual parameter (argument) for each formal
parameter, agreeing as to type. The compiler will check.
A method may return a value.
So a method must have a type---the type of the value it will return,
or void
if it doesn't return a value, just does something.
Some common methods:
- Constructor
- Creates a new instance of the class.
public Class(formal parameters){...}
- Accessor
- Returns the value of an instance variable or a class variable.
public Type getVariable(){...}
- Mutator
- Changes the value of an instance variable or a class variable.
public void setVariable(formal parameters){...}
- Main
- Starting point of an application.
public static void main (String[] args) {...}
- Scope and Lifetime
- Scope is the spatial extent of the source code where a
variable can be referred to by its name.
- Lifetime is the temporal extent in the run of the program
during which a variable retains the
last value it was assigned.
Scope:
- Class and instance variables
- Scope is the entire class definition (the block in which they are
declared). But a static (class) method cannot refer to an instance variable.
- Method variables
- Scope is from the point they are declared through the block in which
they are declared. For the method variables we've seen so far, this
is the entire rest of the method body.
- Formal parameters
- Scope is the body of the method for which they are formal parameters.
Lifetime:
- Class and instance variables
- Lifetime is the entire run of the program (as long as any
variable contains a reference to the instance or any instance of the
class).
- Method variables
- Lifetime is while the method is executing.
- Formal parameters
- Lifetime is while the method is executing.
We will look at the ParameterDemo package containing the
classes StringHolder and ParameterTest.
Note the documentation created
by javadoc from the comments.
Copyright © 2001 by Stuart C. Shapiro. All rights
reserved.