Menu
Coddy logo textTech

Book Class with Composition

Part of the Object Oriented Programming section of Coddy's JavaScript journey. Lesson 51 of 56.

challenge icon

Challenge

Create Book Class with Composition

Your task:

  1. In the file called Book.js import the Author class at the top
  2. Create and export a Book class with:
    • Private fields: #title, #author, #isCheckedOut
    • Constructor that takes title and author
    • Two getters: title and authorInfo that returns the author's name
  3. In main.js, add the import for Book class

How Composition is Applied Here:

Composition means "has-a" relationship. In our Book class:

  • Book HAS-AN Author (not "is-an" Author)
  • The Book contains an Author instance as one of its components
  • The Author exists separately and can be used by multiple Books
  • This is composition: building complex objects (Book) from simpler ones (Author)

Try it yourself

import { Author } from './Author.js';

// TODO:  Import the Book class

// Tests
const author = new Author('J.K. Rowling');
const book = new Book('Harry Potter', author);

console.log('Book title:', book.title); // Should output: "Book title: Harry Potter"
console.log('Author:', book.authorInfo); // Should output: "Author: J.K. Rowling"

All lessons in Object Oriented Programming

Practice on your own: Online JavaScript compiler