Java Reference
In-Depth Information
Self-Test Exercises
(continued)
23.
Consider the class
DateSixthTry
in Display 4.11. Would it be legal to add
two method defi nitions with the following two method headings to the class
DateSixthTry
?
public int
getMonth()
public
String getMonth()
4.4
Constructors
Well begun is half done.
Proverb
You often want to initialize the instance variables for an object when you create
the object. As you will see later in this topic, there are other initializing actions you
might also want to take, but initializing instance variables is the most common sort of
initialization. A
constructor
is a special variety of method that is designed to perform
such initialization. In this section, we tell you how to define and use constructors.
constructor
Constructor Definitions
Although you may not have realized it, you have already been using constructors every
time you used the
new
operator to create an object, as in the following example:
DateSixthTry date1 =
new
DateSixthTry();
The expression
new DateSixthTry()
is an invocation of a constructor. A constructor
is a special variety of method that, among other things, must have the same name as
the class. So, the first occurrence of
DateSixthTry
in the previous code is a class name,
and the second occurrence of
DateSixthTry
is the name of a constructor. If you add
no constructor definitions to your class, then Java automatically creates a constructor
that takes no arguments. We have been using this automatically provided constructor
up until now. The automatically provided constructor creates the object but does little
else. It is preferable to define your own constructors so that you can have the constructor
initialize instance variables, or do whatever other initialization actions you want.
In Display 4.13, we have rewritten our date class one last time by adding five con-
structors. Since this is our final date class, we have included all method definitions in
the display so you can see the entire class definition. (We have omitted
writeOutput
because it would be superfluous, as noted in the earlier subsection entitled “The
Methods
equals
and
toString
.” )