Composition of Classes

An object can have references to objects of other classes. This is called composition or a has-a relationship. In UML, this might be modeled as an association, aggregration or "composition"* relationship, depending on how strong the relationship is. [*"Composition" in UML means something different from "composition" of classes. It's confusing, but that's the way it is.]

The example used in this web page is Employee objects having references to Date objects. This example can be downloaded into Eclipse using this project file.

Employee.java has fields for the employee's first name, last name, birth date, and date of hire: two String objects and two Date objects. A Date object, as defined by Date.java, has fields for month, day of month, and year: all ints. EmployeeTest.java creates two Date objects, which are then used to create an Employee object.

In a UML class diagram, there would be dependency relationships from EmployeeTest to Employee and Date, and an aggregation relationship from Employee to Date. The UML aggregation relationship seems better than the association relationship because dates can be viewed as part of the employee (or at least as part of the employee's PII (personally identifiable information)). It is not composition because the same Date object could be used by several objects. The aggregation relationship should have an arrow pointing to Date because it is unidirectional, but VioletUML lacks this capability. (Violet UML Diagram)

There are a few interesting things about the Date class.

Date.java has a class constant to indicate the number of days in each month. Only indexes 1 through 12 will be used, so the value at index 0 does not matter. Also, leap year is an issue that will be handled in the code.

The first part of the constructor performs some input validation, making sure that the month is between 1 and 12, and the day is a legal day of for that month. What might happen if the month is validated last instead of first?

If the month or day is invalid, then the code will result in a runtime error, that is, the code will throw an exception. In this case, it will throw an IllegalArgumentException. The main method in EmployeeTest.java does not handle this exception, so the program will crash if given a bad date.