Java Reference
In-Depth Information
20
21
// check if day in range for month
22
if
(day <=
0
||
23
(day > daysPerMonth[month] && !(month ==
2
&& day ==
29
)))
24
throw new
IllegalArgumentException(
"day ("
+ day +
25
") out-of-range for the specified month and year"
);
26
27
// check for leap year if month is 2 and day is 29
28
if
(month ==
2
&& day ==
29
&& !(year %
400
==
0
||
29
(year %
4
==
0
&& year %
100
!=
0
)))
30
throw new
IllegalArgumentException(
"day ("
+ day +
31
") out-of-range for the specified month and year"
);
32
33
this
.month = month;
34
this
.day = day;
35
this
.year = year;
36
37
System.out.printf(
38
"Date object constructor for date %s%n"
,
this
);
39
}
40
41
// return a String of the form month/day/year
42
public
String toString()
43
{
44
return
String.format(
"%d/%d/%d"
, month, day, year);
45
}
46
}
// end class Date
Fig. 8.7
|
Date
class declaration. (Part 2 of 2.)
Class
Employee
Class
Employee
(Fig. 8.8) has instance variables
firstName
,
lastName
,
birthDate
and
hireDate
. Members
firstName
and
lastName
are references to
String
objects. Members
birthDate
and
hireDate
are references to
Date
objects. This demonstrates that a class can
have as instance variables references to objects of other classes. The
Employee
constructor
(lines 12-19) takes four parameters representing the first name, last name, birth date and
hire date. The objects referenced by the parameters are assigned to the
Employee
object's
instance variables. When class
Employee
's
toString
method is called, it returns a
String
containing the employee's name and the
String
representations of the two
Date
objects.
Each of these
String
s is obtained with an
implicit
call to the
Date
class's
toString
method.
1
// Fig. 8.8: Employee.java
2
// Employee class with references to other objects.
3
4
public class
Employee
5
{
6
private
String firstName;
7
private
String lastName;
8
private
Date birthDate;
private
Date hireDate;
9
Fig. 8.8
|
Employee
class with references to other objects. (Part 1 of 2.)