Java Reference
In-Depth Information
illustrated in Figure 2.4 by the arrow labeled (B). The right-hand side is called an expression. In
their most general form, expressions are things that compute value, but in this case, the expres-
sion consists of just a single variable, whose value is copied into the price variable. We shall
see examples of more-complicated expressions later in this chapter.
One rule about assignment statements is that the type of the expression on the right-hand side
must match the type of the variable to which it is assigned. We have already met three differ-
ent, commonly used types: int , String , and (very briefly) boolean . This rule means that we
are not allowed to store an int -type expression in a String -type variable, for instance. This
same rule also applies between formal parameters and actual parameters: the type of an actual-
parameter expression must match the type of the formal-parameter variable. For now, we can
say that the types of both must be the same, although we shall see in later chapters that this is
not the whole truth.
Exercise 2.21 Suppose that the class Pet has a field called name that is of type String .
Write an assignment statement in the body of the following constructor so that the name field
will be initialized with the value of the constructor's parameter.
public Pet(String petsName)
{
}
Exercise 2.22 Challenge exercise The following object creation will result in the constructor
of the Date class being called. Can you write the constructor's header?
new Date("March", 23, 1861)
Try to give meaningful names to the parameters.
2.7
Methods
The TicketMachine class has four methods: getPrice , getBalance , insertMoney , and
printTicket . We shall start our look at the source code of methods by considering getPrice
(Code 2.5).
Concept:
Methods consist
of two parts: a
header and a body.
Methods have two parts: a header and a body. Here is the method header for getPrice , pre-
ceded by a descriptive comment:
/**
* Return the price of a ticket.
*/
public int getPrice()
It is important to distinguish between method headers and field declarations, because they
can look quite similar. We can tell that getPrice is a method and not a field because method
headers always include a pair of parentheses - “(” and “)” - and no semicolon at the end of the
header.
 
 
Search WWH ::




Custom Search