Book and User Classes
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 78 of 87.
Challenge
EasyLet's continue building the Library Management System by expanding the Book and User classes from the previous lesson. Now you'll add the ability for users to borrow books, creating a real connection between these two entities.
You'll organize your code across three files:
Book.java: Enhance your Book class from the previous challenge. Keep all existing functionality (isbn, title, author, isAvailable with getters/setters, andgetDetails()). Now add a private fieldborrowedByof typeStringthat stores the ID of the user who borrowed the book (ornullif not borrowed). Add a getter forborrowedByand a setter that also updatesisAvailableaccordingly—when a book is borrowed (borrowedBy is set to a non-null value), it becomes unavailable; when returned (set to null), it becomes available again.User.java: Expand your User class to track borrowed books. Keep the existing id, name, constructor, getters, andtoString(). Add a privateArrayList<Book>field calledborrowedBooks(initialize it in the constructor). Create aborrowBook(Book book)method that adds the book to the user's list and sets the book'sborrowedByto this user's ID. Create areturnBook(Book book)method that removes the book from the list and setsborrowedByto null. Add agetBorrowedCount()method that returns how many books the user currently has.Main.java: Demonstrate the borrowing system in action. You'll receive five inputs: ISBN, title, author for a book, then user ID and name.Create a Book and a User with these inputs. Print the book's details and availability status. Then have the user borrow the book. Print the book's availability again, followed by who borrowed it in the format
Borrowed by: [userId]. Print how many books the user has in the format[name] has [count] book(s). Finally, have the user return the book and print the availability one more time.
You will receive five inputs in order: ISBN (String), title (String), author (String), user ID (String), and user name (String).
For example, with inputs 978-0-13-468599-1, Effective Java, Joshua Bloch, U001, and Alice, your output would be:
[978-0-13-468599-1] Effective Java by Joshua Bloch
Available: true
Available: false
Borrowed by: U001
Alice has 1 book(s)
Available: trueThis challenge builds directly on your previous work, adding the crucial relationship between books and users that makes a library system functional. You'll use composition (User "has" Books) and see how changes to one object can affect another through well-designed methods!
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read book information
String isbn = scanner.nextLine();
String title = scanner.nextLine();
String author = scanner.nextLine();
// Read user information
String userId = scanner.nextLine();
String userName = scanner.nextLine();
// Create a Book object with isbn, title, and author
Book book = new Book(isbn, title, author);
// Create a User object with userId and userName
User user = new User(userId, userName);
// Print the book's details using getDetails()
System.out.println(book.getDetails());
// Print whether the book is available (format: "Available: true" or "Available: false")
System.out.println("Available: " + book.isAvailable());
// Have the user borrow the book
user.borrowBook(book);
// Print the book's availability again
System.out.println("Available: " + book.isAvailable());
// Print who borrowed it
System.out.println("Borrowed by: " + book.getBorrowedBy());
// Print how many books the user has
System.out.println(user.getName() + " has " + user.getBorrowedCount() + " book(s)");
// Have the user return the book
user.returnBook(book);
// Print the availability one more time
System.out.println("Available: " + book.isAvailable());
}
}All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting10Exception Handling in OOP
Exception Class HierarchyCustom ExceptionsChecked vs Unchecked ErrorsTry With Resources PatternRecap - Validated User13Project: Library Management
Project Overview & UML DesignBook and User Classes2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System