Menu
Coddy logo textTech

Book and User Classes

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 102 of 110.

challenge icon

Challenge

Easy

In the previous lesson, you created a Book class with basic properties and a toString() method. Now it's time to expand your library system by adding a User class to represent library members who can borrow books.

You'll need to create a new file and update your existing files:

  • book.dart: Enhance your existing Book class by adding an isAvailable property (boolean) that defaults to true. This will track whether a book can be borrowed.
  • user.dart: Create a new User class to represent library members. Each user should have an id (String), name (String), and a borrowedBooks list that holds Book objects. Include a constructor that initializes the id and name, with an empty list for borrowed books. Override toString() to return the format User [id]: name (X books borrowed) where X is the count of borrowed books.
  • main.dart: Import both your book and user files. Create a book with ISBN 978-0-13-468599-1, title The Pragmatic Programmer, and author David Thomas. Create a user with id U001 and name Alice Johnson. Print the book, then print whether it's available using the format Available: true or Available: false. Print the user. Then add the book to the user's borrowed books list, set the book's isAvailable to false, and print the user again to show the updated book count.

This establishes the relationship between books and users that you'll build upon when implementing the full borrowing system in the next lesson!

Expected output:

[978-0-13-468599-1] The Pragmatic Programmer by David Thomas
Available: true
User U001: Alice Johnson (0 books borrowed)
User U001: Alice Johnson (1 books borrowed)

Try it yourself

import 'book.dart';
// TODO: Import user.dart

void main() {
  // TODO: Create a book with ISBN '978-0-13-468599-1', title 'The Pragmatic Programmer', and author 'David Thomas'
  
  // TODO: Create a user with id 'U001' and name 'Alice Johnson'
  
  // TODO: Print the book
  
  // TODO: Print whether the book is available using format: Available: true/false
  
  // TODO: Print the user
  
  // TODO: Add the book to the user's borrowedBooks list
  
  // TODO: Set the book's isAvailable to false
  
  // TODO: Print the user again to show updated book count
}

All lessons in Object Oriented Programming