Java Reference
In-Depth Information
Code 2.5
The
getPrice
method
public
class
TicketMachine
{
Fields omitted.
Constructor omitted.
/**
* Return the price of a ticket.
*/
public
int
getPrice()
{
return
price;
}
Remaining methods omitted.
}
The method body is the remainder of the method after the header. It is always enclosed by
a matching pair of curly brackets: “{“ and “}”. Method bodies contain the
declarations
and
statements
that define what an object does when that method is called. Declarations are used
to create additional, temporary variable space, while statements describe the actions of the
method. In
getPrice
, the method body contains a single statement, but we shall see examples
very soon where the method body consists of many lines of both declarations and statements.
Any set of declarations and statements between a pair of matching curly brackets is known as a
block.
So the body of the
TicketMachine
class and the bodies of the constructor and all of the
methods within the class are blocks.
There are at least two significant differences between the headers of the
TicketMachine
con-
structor and the
getPrice
method:
public TicketMachine(int cost)
public int getPrice()
■
The method has a
return type
of
int
, but the constructor has no return type. A return type is
written just before the method name. This is a difference that applies in all cases.
■
The constructor has a single formal parameter,
cost
, but the method has none—just a pair of
empty parentheses. This is a difference that applies in this particular case.
It is an absolute rule in Java that a constructor may not have a return type. On the other hand,
both constructors and methods may have any number of formal parameters, including none.
Within the body of
getPrice
there is a single statement:
return price;
This is a called a
return statement.
It is responsible for returning an integer value to match
the
int
return type in the method's header. Where a method contains a return statement, it is
always the final statement of that method, because no further statements in the method will be
executed once the return statement is executed.
Search WWH ::
Custom Search