Book model
- Java course
- Intermediate
- Lesson 20/116
- 6 min
Write the Book class and constructor.
The Book model
The second lesson defines the Book class. Each book has a title and an author. The Book class represents books in the library; its constructor takes title and author parameters.
Example: class Book { String title; String author; Book(String t, String a) { title = t; author = a; } }. This class is added alongside the Library class. A toString method shows the book readably: title + " - " + author. Later a book list will be added to Library; for now defining a single book is enough.
Two classes side by side
You now have two classes: Library and Book. Both can be defined in the same file. By putting the main method inside Book, you can create and print a book instance. The previous lesson's solution is included in the starting code.
Example: The file first holds the Library class, then the Book class. In Book's main method, a book is created with new Book("Java", "Gosling"). This structure shows that the project grows by adding one class each lesson. The Library class stays unchanged; new classes are added beside it.
Practice Add the Book class
Add a Book class to the file. Write String title and String author fields. Add a Book(String t, String a) constructor; assign both fields. Add a public String toString() method returning title + " - " + author. Put main inside Book; create a Book instance and print it.
Starter code
class Library {
String name;
Library(String n) {
name = n;
}
public String toString() {
return "Library: " + name;
}
}
// Add the Book class
// title and author fields, constructor and toString
// Instantiate and print in mainSample solution
class Library {
String name;
Library(String n) {
name = n;
}
public String toString() {
return "Library: " + name;
}
}
class Book {
String title;
String author;
Book(String t, String a) {
title = t;
author = a;
}
public String toString() {
return title + " - " + author;
}
public static void main(String[] args) {
Book b = new Book("Java", "Gosling");
System.out.println(b);
}
}Expected output
Java - Gosling
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 |
Title field |
String author |
Author field |
Book(String t, String a) |
Constructor |
title + author |
toString body |
2 How many parameters does the Book constructor take?
- 0
- 1
- 2 Correct answer
- 3
Explanation: answer: 2. Book(String t, String a) takes two parameters.
3 Complete the Book toString body
public String toString() {
return title + " - " + ____;
}
public String toString() {
return title + " - " + author;
}
Explanation: The author field is added next to the title.