0/30 Days Completed 0 Learning Days
Day 28 of 30 · Week 4 — OOPs Through Java
Integrated OOPS practice: Library System
Practical review day1 Learn
Review day! This small library program uses an interface, an abstract class, inheritance, encapsulation, constructors and overriding together.
Read it slowly and find each concept — then extend it with the challenges below.
2 See the Code
Java
interface Borrowable {
boolean borrow();
}
abstract class Item implements Borrowable {
private final String title;
private boolean out = false;
Item(String title) { this.title = title; }
String getTitle() { return title; }
public boolean borrow() {
if (out) return false;
out = true;
return true;
}
abstract int loanDays();
}
class Book extends Item {
Book(String t) { super(t); }
int loanDays() { return 14; }
}
class Magazine extends Item {
Magazine(String t) { super(t); }
int loanDays() { return 3; }
}
public class Library {
public static void main(String[] args) {
Item[] items = { new Book("Code Garden"), new Magazine("Tech Weekly") };
for (Item i : items) {
System.out.println(i.getTitle() + ": " + i.loanDays() + " days, borrowed=" + i.borrow());
}
System.out.println("Again: " + items[0].borrow());
}
}- Interface: Borrowable. Abstract class: Item. Inheritance: Book and Magazine extend Item.
- Encapsulation: title and out are private and changed only through methods.
- Polymorphism: loanDays() gives a different answer for each item type.
Output
Code Garden: 14 days, borrowed=true Tech Weekly: 3 days, borrowed=true Again: false
3 Practice
- Challenge 1: Add a giveBack() method that sets out back to false.
- Challenge 2: Add a DVD class with 7 loan days.
- Challenge 3: Count how many items are currently borrowed using a loop.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. Which concept makes loanDays() differ by item type?
2. Why is title private?
3. Why does the second borrow() return false?
Step 5
Answer and check the Quick Check above to unlock this.