8.8 Composition

A class can have references to objects of other classes as members. This is called composition and is sometimes referred to as a has-a relationship. For example, an AlarmClock object 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.

Class Date

This composition example contains classes Date (Fig. 8.7), Employee (Fig. 8.8) and Employ-eeTest (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. Line 17 invokes utility method checkMonth (lines 26–32) to validate the month—if the value is out-of-range the ...

Get Java How to Program (early objects), 9/e now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.