Java Reference
In-Depth Information
Display 4.15 Use of Constructors
Sample Dialogue
Whose birthday is December 16, 1770?
Whose birthday is January 27, 1756?
Whose birthday is January 1, 1882?
The default date is January 1, 1000.
Is a Constructor Really a Method?
There are differing opinions on whether or not a constructor should be called a method.
Most authorities call a constructor a method but emphasize that it is a special kind of
method with many properties not shared with other kinds of methods. Some authorities say
a constructor is a method-like entity but not, strictly speaking, a method. All authorities
agree about what a constructor is; the only disagreement is over whether or not it should be
referred to as a method. Thus, this is not a major issue. However, whenever you hear a
phrase like “all methods,” you should make sure you know whether it does or does not
include constructors. To avoid confusion, we try to use the phrase “constructors and meth-
ods” when we want to include constructors.
TIP: You Can Invoke Another Method in a Constructor
It is perfectly legal to invoke another method within the definition of a constructor. For
example, several of the constructors in Display 4.13 invoke a mutator method to set
the values of the instance variables. This is legal because the first action taken by a con-
structor is to automatically create an object with instance variables. You do not write
any code to create this object. Java creates it automatically when the constructor is
invoked. Any method invocation in the body of the constructor definition has this
object as its calling object.
You can even include an invocation of one constructor within the definition of
another constructor. However, we will not discuss the syntax for doing that in this
chapter. It will be covered in Chapter 7.
TIP: A Constructor Has a this Parameter
Just like the ordinary methods we discussed before we introduced constructors, every
constructor has a this parameter. The this parameter can be used explicitly, but it is
more often understood to be present although not written down. Whenever an
instance variable of the class is used in a constructor (without an object name and a dot
before it), it is understood to have an implicit this and dot before it. Similarly, when-
 
Search WWH ::




Custom Search