Lesson 19Diving into Composition

In this very short lesson, we'll take an initial look at what composition looks like in Java code. In Lesson 17, we discussed how composition can be used to model a has-a relationship between objects. In this lesson, we will look at a simple example of composition.

Later in this part of the course, we'll explore the power of composition after we learn about the List and Maps data structures in Lessons 21 and 22. We'll use these data structures and composition to create components later in this course.

WHAT IS COMPOSITION?

One of the main characteristics of an object-oriented language is that objects can be made up of other objects. This is done through composition. From a coding standpoint, this means that one or more of the fields in an object are other objects rather than primitive types or strings.

To illustrate this point, look at two examples of modeling a book in Java. In each model, we want to keep track of the following:

  • Book title
  • Book ISBN
  • Book author, including contact information
  • Book publisher, including contact information

Book without Composition

Let's start with an example that does not use composition, which we'll call BadBook. In the BadBook class, we will model all the information about the book using strings. It might look something like Listing ...

Get Job Ready Java 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.