Classes
- Dart course
- Beginner
- Lesson 113/116
- 6 min
Set up the data model with class and constructor.
Classes
Now we will add the Book class. A book has a title; so we will write a String title field and a Book(this.title) constructor. This way we can represent books in our library.
Classes model real-world objects in code. Book represents a book, Library a library. Each class carries its own fields and behavior. In an application many classes work side by side; one uses another. In this lesson we will use both Library and Book together.
Using two classes together
Many classes can be defined side by side in a single file. The Library and Book classes can work together. In main you create objects from both and use them together. For example you can create a book and print its title below the library info.
This approach is the foundation of large applications. Each class does one thing well; classes talk to each other. In this lesson Library represents the library, Book a book; main brings them together. In the next lesson we will gather books in a list.
Practice Add the Book class
The Library class is already defined in the code below. Now define the Book class: a String title field and a Book(this.title) constructor. In main create a book with final b = Book("Crime and Punishment"); and print "New book: ${b.title}".
Starter code
class Library {
String name;
Library(this.name);
void info() {
print("Library: $name");
}
}
void main() {
final lib = Library("City");
lib.info();
// define the Book class and print a book
}Sample solution
class Library {
String name;
Library(this.name);
void info() {
print("Library: $name");
}
}
class Book {
String title;
Book(this.title);
}
void main() {
final lib = Library("City");
lib.info();
final b = Book("Crime and Punishment");
print("New book: ${b.title}");
}Expected output
Library: City New book: Crime and Punishment
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The Book class
____ Book {
String title;
Book(this.title);
}
class Book {
String title;
Book(this.title);
}
Explanation: class Book starts the definition.
2 How is the Book constructor written?
class Book {
String title;
____
}- Book(this.title)
- Book() Correct answer
- new Book()
- title()
Explanation: the Book(this.title) constructor assigns the title field.
3 Match class usage
| Term | Meaning |
|---|---|
Library |
carries the library |
Book |
carries a book |
main |
brings together |
lib.info() |
prints library info |