Java Reference
In-Depth Information
The black-box view of a method
You know that a method is the programming equivalent of a recipe. We now see
how methods are used in Java.
The anatomy of a method header
The definition of a method has three parts: specification, header, and body. Here,
we describe the first two parts, which are used to understand a call on a method.
When you call a method, we say that you are the client or customer of the
method. Below is a method definition, with the contents of the body not shown:
/** Draw a line in graphics window from
pixel (x1, y1) to (x2, y2) */
public void drawLine( int x1, int y1, int x2, int y2) {
The first part of a method declaration is a comment that describes what the
method does. It is called a specification . As you can see from the specification
given above, method drawLine draws a line in the graphics window.
The second part of a method declaration is the method header , which con-
tains (in order) these items:
Style Note
method names
Modifiers . In this header, the one modifier, public , indicates that every
class can use this method. (You will see private methods later on.)
The return type . Keyword void indicates that this method is a proce-
dure , which is a method that does not return a value. For a function , the
type of value the function returns replaces void .
The name of the method , in this case, drawLine .
Declarations of the parameters of the method, enclosed in parentheses
and separated by commas. Each parameter declaration consists of a type
and the name of the parameter (which is an identifier). In this case, all
four parameters — x1 , y1 , x2 , and y2 — are of type int .
The signature of a method consists of the name of the method and the num-
ber and types of is parameters. We write the signature of drawLine as follows:
drawLine( int , int , int , int )
The idea of a parameter was discussed in Sec. 2.1 when relating methods to
recipes. There, a parameter X was associated with a value —a bunch of prunes or
apricots. Similarly, in Java, a value gets associated with the parameter when the
method is called. The idea of a parameter may still seem foreign to you, so we
recommend that you memorize the following definition:
Style Note
Parameter : A parameter is a variable that is declared within the
parentheses of a method header.
Search WWH ::

Custom Search