Java Reference
In-Depth Information
In Display 4.13, we have used overloading to create five constructors for the class
Date
. It is normal to have more than one constructor. Since every constructor must
have the same name as the class, all the constructors in a class must have the same
name. So, when you define multiple constructors, you must use overloading.
Note that when you define a constructor, you do not give any return type for the
constructor; you do not even use
void
in place of a return type. Also notice that con-
structors are normally public.
All the constructor definitions in Display 4.13 initialize all the instance variables,
even if there is no parameter corresponding to that instance variable. This is normal.
In a constructor definition, you can do pretty much anything that you can do in
any ordinary method definition, but normally you only perform initialization tasks
such as initialization of instance variables.
When you create a new object with the operator
new
, you must always include the
name of a constructor after the operator
new
. This is the way you invoke a constructor.
As with any method invocation, you list any arguments in parentheses after the con-
structor name (which is the same as the class name). For example, suppose you want to
use
new
to create a new object of the class
Date
defined in Display 4.13. You might do
so as follows:
constructor
arguments
Date birthday =
new
Date("December", 16, 1770);
This is a call to the constructor for the class
Date
that takes three arguments: one of
type
String
and two of type
int
. This creates a new object to represent the date
December 16, 1770, and sets the variable
birthday
so that it names this new object.
Another example is the following:
Date newYearsDay =
new
Date(3000);
This creates a new object to represent the date January 1, 3000, and sets the variable
newYearsDay
so that it names this new object.
Constructor
A
constructor
is a variety of method that is called when an object of the class is created
using
new
. Constructors are used to initialize objects. A constructor must have the same
name as the class to which it belongs. Arguments for a constructor are given in parentheses
after the class name, as in the following examples.
EXAMPLES
Date birthday =
new
Date("December", 16, 1770),
theDate =
new
Date(2008);
A constructor is defined very much like any ordinary method except that it does not have a
type returned and does not even include a
void
in the constructor heading. See Display
4.13 for examples of constructor definitions.