Java
Book model
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.
Exercise 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.
Show example 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);
}
}
Test yourself
-
Match the Book parts
- String title
- Title field
- String author
- Author field
- Book(String t, String a)
- Constructor
- title + author
- toString body
-
How many parameters does the Book constructor take?
Show answer
2 — answer: 2. Book(String t, String a) takes two parameters.
-
Complete the Book toString body
public String toString() {
return title + " - " + ____;
}
Show answer
public String toString() {
return title + " - " + author;
}
Next lesson: Member management