WeCodeAcademy

Step 2: The Book class

Start with the data. A Book has an ISBN, title and author that never change (final) and an available flag that does. Fields are private and reached through getters and a setter, and toString produces a readable description (which println uses automatically).

ExampleJava
import java.util.*;

public class Main {
  static class Book {
    private final String isbn;
    private final String title;
    private final String author;
    private boolean available = true;

    Book(String isbn, String title, String author) {
      this.isbn = isbn;
      this.title = title;
      this.author = author;
    }

    String getIsbn() { return isbn; }
    String getTitle() { return title; }
    String getAuthor() { return author; }
    boolean isAvailable() { return available; }
    void setAvailable(boolean available) { this.available = available; }

    @Override
    public String toString() {
      return title + " by " + author + (available ? "" : " (on loan)");
    }
  }

  public static void main(String[] args) {
    Book b = new Book("978-0", "Clean Code", "Robert Martin");
    System.out.println(b);
    b.setAvailable(false);
    System.out.println(b);
    System.out.println(b.getIsbn() + " " + b.isAvailable());
  }
}
Output
Clean Code by Robert Martin
Clean Code by Robert Martin (on loan)
978-0 false

Keeping fields private means no other code can put a Book into an invalid state; they can only use the methods you provide. This is encapsulation.

Quick check

Why are the Book fields private?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.