Java Reference
In-Depth Information
Predicate Methods
Another common use for accessor methods is to test whether a condition is true or false
such methods are often called predicate methods. An example would be class ArrayList 's
isEmpty method, which returns true if the ArrayList is empty and false otherwise. A
program might test isEmpty before attempting to read another item from an ArrayList .
8.8 Composition
A class can have references to objects of other classes as members. This is called composi-
tion and is sometimes referred to as a has-a relationship . For example, an AlarmClock ob-
ject needs to know the current time and the time when it's supposed to sound its alarm,
so it's reasonable to include two references to Time objects in an AlarmClock object. A car
has-a steering wheel, a break pedal and an accelerator pedal.
Class Date
This composition example contains classes Date (Fig. 8.7), Employee (Fig. 8.8) and Em-
ployeeTest (Fig. 8.9). Class Date (Fig. 8.7) declares instance variables month , day and
year (lines 6-8) to represent a date. The constructor receives three int parameters. Lines
17-19 validate the month —if it's out-of-range, lines 18-19 throw an exception. Lines 22-
25 validate the day . If the day is incorrect based on the number of days in the particular
month (except February 29th which requires special testing for leap years), lines 24-25
throw an exception. Lines 28-31 perform the leap year testing for February. If the month
is February and the day is 29 and the year is not a leap year, lines 30-31 throw an excep-
tion. If no exceptions are thrown, then lines 33-35 initialize the Date's instance variables
and lines 38-38 output the this reference as a String . Since this is a reference to the
current Date object, the object's toString method (lines 42-45) is called implicitly to ob-
tain the object's String representation. In this example, we assume that the value for year
is correct—an industrial-strength Date class should also validate the year.
1
// Fig. 8.7: Date.java
2
// Date class declaration.
3
4
public class Date
5
{
6
private int month; // 1-12
7
private int day; // 1-31 based on month
8
private int year; // any year
9
10
private static final int [] daysPerMonth =
11
{ 0 , 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 };
12
13
// constructor: confirm proper value for month and day given the year
14
public Date( int month, int day, int year)
15
{
16
// check if month in range
17
if (month <= 0 || month > 12 )
18
throw new IllegalArgumentException(
19
"month (" + month + ") must be 1-12" );
Fig. 8.7 | Date class declaration. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search