Java Reference
In-Depth Information
SR 4.20
Explain the difference between an actual parameter and a formal
parameter.
SR 4.21
Write a method called
getFaceDown
for the
Die
class that returns the
current “face down” value of the die.
Hint:
On a standard die, the
sum of any two opposite faces is seven.
SR 4.22
In the
Transactions
program:
a. How many
Account
objects are created?
b. How many arguments (actual parameters) are passed to the
withdraw
method when it is invoked on the
acct2
object?
c. How many arguments (actual parameters) are passed to the
addInterest
method when it is invoked on the
acct3
object?
SR 4.23
Which of the
Account
class methods would you classify as accessor
methods? As mutator methods? As service methods?
As we stated in Chapter 2, a constructor is similar to a method that is invoked
when an object is instantiated. When we define a class, we usually define a con-
structor to help us set up the class. In particular, we often use a constructor to
initialize the variables associated with each object.
A constructor differs from a regular method in two ways. First, the name of a
constructor is the same name as the class. Therefore the name of the constructor
in the
Die
class is
Die
, and the name of the constructor in the
Account
class is
Account
. Second, a constructor cannot return a value and does not have a return
type specified in the method header.
A common mistake made by programmers is to put a
void
return
type on a constructor. As far as the compiler is concerned, putting
any return type on a constructor, even
void
, turns it into a regular
method that happens to have the same name as the class. As such, it cannot be
invoked as a constructor. This leads to error messages that are sometimes difficult
to decipher.
Generally, a constructor is used to initialize the newly instantiated object. For
instance, the constructor of the
Die
class sets the face value of the die to 1 initially.
The constructor of the
Account
class sets the values of the instance variables to
the values passed in as parameters to the constructor.
We don't have to define a constructor for every class. Each class has a
default
constructor
that takes no parameters. The default constructor is used if we don't
KEY CONCEPT
A constructor cannot have any return
type, even
void
.
Search WWH ::
Custom Search