CodeBlanks Logo Icon CodeBlanks

Model design

Design the skeleton of Book and Member classes.

Project: Library app

In this project you will build a library app. Each lesson adds a piece and the final lesson yields a working console app. The first step is the Book class that represents a single book.

A Book has two fields: String title (the book name) and bool borrowed (is it lent out?). When a Book is created borrowed defaults to false. The constructor Book(this.title) sets the title.

In the next lessons we will add a Library class, checkout and search methods. Starting with a solid model matters.

The Book class skeleton

The Book class looks like this: class Book { String title; bool borrowed = false; Book(this.title); }. The title is set by the constructor; borrowed keeps its default false.

Here bool borrowed = false gives the field an initial value. Book(this.title) is the short constructor; it assigns the title parameter straight to the field.

To use the Book write var b = Book('Les Miserables');. Read the name with b.title and the status with b.borrowed. The next lessons gather these Books in a list.

Practice Define the Book class

Define a Book class with String title, bool borrowed = false fields and a Book(this.title) constructor. Inside main create a Book('Les Miserables') instance; print title and borrowed on separate lines.

Starter code

main.dart
void main() {
  // define the Book class (outside main)

  // create an instance and print title and borrowed
}

Sample solution

main.dart
class Book {
  String title;
  bool borrowed = false;
  Book(this.title);
}

void main() {
  var b = Book('Les Miserables');
  print(b.title);
  print(b.borrowed);
}

Expected output

Les Miserables
false

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the Book parts

Term Meaning
String title Book name
bool borrowed Lent status
Book(this.title) Constructor
false Initial value

2 What is borrowed on a new Book?

  • false Correct answer
  • true
  • null
  • Throws

Explanation: on a new Book borrowed defaults to false.

3 Book constructor

Question
class Book {
  String title;
  bool borrowed = false;
  ____(this.title);
}
Answer
class Book {
  String title;
  bool borrowed = false;
  Book(this.title);
}

Explanation: the constructor shares the class name.

All lessons in Intermediate