Complete the Book Class
In this exercise, you'll be creating a fundamental building block for a library management system. This task will help you practice object-oriented programming concepts in Java, including class design, method implementation, and state management. By completing this challenge, you'll gain valuable experience in creating practical, real-world applications. Let's dive into the world of virtual books!
Tasks
- Open the pre-created file
Book.java
in the ~/project
directory.
- Find the TODO comments in the code.
- Add the missing code to complete the
Book
class as per the requirements.
Requirements
- The file
Book.java
should already exist in the ~/project
directory.
- Complete the constructor to initialize all the fields (title, author, publicationYear, and isAvailable).
- Implement the
borrowBook()
method:
- If the book is available, set isAvailable to false and return true.
- If the book is not available, return false.
- Implement the
returnBook()
method:
- Implement the
getFormattedBookDetails()
method:
- Return a string containing the book's title, author, and publication year.
- The format should be: "Title by Author (Year)"
Example
When completed correctly, the following code in the main
method:
Book book = new Book("Java Programming", "John Doe", 2023);
System.out.println(book.getFormattedBookDetails());
System.out.println("Is book available? " + book.isAvailable());
boolean borrowed = book.borrowBook();
System.out.println("Book borrowed successfully? " + borrowed);
System.out.println("Is book available now? " + book.isAvailable());
book.returnBook();
System.out.println("Is book available after return? " + book.isAvailable());
Should produce output similar to this:
cd ~/project
javac Book.java
java Book
Sample Output:
Java Programming by John Doe (2023)
Is book available? true
Book borrowed successfully? true
Is book available now? false
Is book available after return? true