Java Reference
In-Depth Information
A constructor is called when you create a new object, such as with the operator
new
.
An attempt to call a constructor in any other way, such as the following, is illegal:
resetting
object
values
birthday.Date("January", 27, 1756); //Illegal!
Because you cannot call a constructor for an object after it is created, you need
some other way to change the values of the instance variables of an object. That is the
purpose of the
setDate
methods and other methods that begin with
set
in Display
4.13. If
birthday
already names an object that was created with
new
, you can change
the values of the instance variables as follows:
birthday.setDate("January", 27, 1756);
Although it is not required, such methods that reset instance variables normally are
given names that start with
set
.
Although you cannot use a constructor to reset the instance variables of an already
created object, you can do something that looks very similar. The following is legal:
Date birthday =
new
Date("December", 16, 1770);
.
.
.
birthday =
new
Date("January", 27, 1756);
However, the second invocation of the constructor does not simply change the values of
instance variables for the object. Instead, it discards the old object and allocates storage
for a new object before setting the instance variables. So, for efficiency (and occasionally
for other reasons we have not yet discussed), it is preferable to use a method such as
setDate
to change the data in the instance variables of an already created object.
Display 4.14 contains a demonstration program for the constructors defined in
Display 4.13.
Display 4.14
Use of Constructors
1
public
class
ConstructorsDemo
2{
3
public static void
main(String[] args)
4
{
5
Date date1 =
new
Date("December", 16, 1770),
6
date2 =
new
Date(1, 27, 1756),
7
date3 =
new
Date(1882),
8
date4 =
new
Date();
9
System.out.println("Whose birthday is " + date1 + "?");
10
System.out.println("Whose birthday is " + date2 + "?");
11
System.out.println("Whose birthday is " + date3 + "?");
12
System.out.println("The default date is " + date4 + ".");
13
}
14
}
(continued)