Reading Class Documentation
The Structure of a Method Declaration
A method declaration gives:
- the method's name
- the types of its parameters and
their order (and descriptive placeholder names)
- the return type of value the
method returns (or
void
if
the method doesn't return a value)
- The example below shows the first two method
declarations in the class documentation for the
Aquarium
class.
A method declaration is also called the method's
signature.
Reading and Calling Methods
Do-Something Methods
- There is a special return type,
void
for methods that
do something but do not return a value.
- The simplest methods have no parameters and no return value.
- From the AquaFish Documentation:
-
...
- Changing Direction:
fish1.changeDir();
fish1.moveForward();
- The method declaration might specify one or more parameters, giving the
type and a descriptive name for each parameter. When calling the
method, provide parameters of the correct type. (Names do not
matter.)
- From the Clock Documentation:
-
- Setting the time:
-
myClock.setHour(10); // Must pass an int parameter
myClock.setMinute(45); // Must pass an int parameter
Return-Something Methods
-
Methods may return a value, in which case it is important to know
what type of value it will be. These methods might or might not
need parameters.
-
Calls to methods that return a value should be embedded in larger
statements or the return value should be captured in a variable.
Otherwise, the return value is lost.
- From the Clock Documentation:
-
- Printing the time after capturing return
values in variables:
-
String hr = myClock.getHH(); // Returns a String
int min = myClock.getMinute(); // Returns an int
System.out.println(hr + ":" + min);
// Might print 09:3 instead of 09:03; Why?
- Embedding the method calls in a larger
statement:
-
System.out.println(myClock.getHH() + ":" +
myClock.getMinute);
// Might print 09:3 instead of 09:03; Why?
Alyce Brady, Kalamazoo College