F.7 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. F.7), Employee (Fig. F.8) and EmployeeTest (Fig. F.9). Class Date (Fig. F.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 method ...

Get Android How to Program, 3/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.