OOP Fundamentals • PolymorphismMedium⏱️ ~3 min

Polymorphism in Action: Library Management System

Domain: Library Management System

Design a system where different types of library items (books, magazines, DVDs) have different borrowing rules and late fee calculations. Polymorphism allows uniform handling while maintaining type-specific behavior.

Design with Polymorphism

LibraryItem
- itemId: String
- title: String
- borrowed: Boolean
+ calculateLateFee(daysLate): Money
+ getMaxBorrowDays(): Integer
+ canRenew(): Boolean
▲
Book
- author: String
- isbn: String
+ calculateLateFee(daysLate): Money
+ getMaxBorrowDays(): Integer
+ canRenew(): Boolean
Magazine
- issueNumber: Integer
- publisher: String
+ calculateLateFee(daysLate): Money
+ getMaxBorrowDays(): Integer
+ canRenew(): Boolean
DVD
- director: String
- duration: Integer
+ calculateLateFee(daysLate): Money
+ getMaxBorrowDays(): Integer
+ canRenew(): Boolean

Client Code Benefits

BorrowingService
function processReturn(item: LibraryItem, returnDate: Date):
  daysLate = calculateDaysLate(returnDate)
  if daysLate > 0:
    fee = item.calculateLateFee(daysLate) // Polymorphic call
    chargeMember(fee)
  item.markAsReturned()

The processReturn method works with any LibraryItem without knowing the specific type. First, Book charges $0.50 per day late. Second, Magazine charges $0.25 per day (lower value). Third, DVD charges $1.00 per day (high demand). Each implementation provides its own calculation logic.

Extensibility Example

Adding a new AudioBook class requires:

First, Create AudioBook extending LibraryItem. Second, Implement the three methods with AudioBook-specific logic. Third, No changes to BorrowingService or any existing code.

Interview Tip: When asked to design a system, explicitly state how polymorphism eliminates conditional logic. Avoid if-else chains checking item types.
💡 Key Takeaways
✓Polymorphism eliminates type-checking conditionals in client code
✓Each subclass implements behavior specific to its domain requirements
✓Client code depends on abstractions (LibraryItem), not concrete types
✓Adding new types requires zero changes to existing processing logic
📌 Interview Tips
1Book: 14-day borrow, $0.50/day late fee
2Magazine: 7-day borrow, $0.25/day late fee, cannot renew
3DVD: 3-day borrow, $1.00/day late fee, high-demand items
← Back to Polymorphism Overview
Polymorphism in Action: Library Management System | Polymorphism - System Overflow