This chapter aims to reinforce the understanding of Object-Oriented Programming (OOP) through a case study, a practical real-world example.
# Case Study: Simple Library System
Let's consider a simple library system. This system needs to manage books, members, and loans.
Let's see how OOP concepts are applied here.
Book Class:
// Class representing a book in the library
public class Book {
private String title;
private String author;
private String isbn;
// Book class constructor
public Book(String title, String author, String isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
// Getters
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getIsbn() {
return isbn;
}
// Setters
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
}
Member Class:
import java.util.List;
import java.util.ArrayList;
// Class representing a library member
public class Member {
private String name;
private String id;
private List<Book> borrowedBooks;
// Member class constructor
public Member(String name, String id) {
this.name = name;
this.id = id;
this.borrowedBooks = new ArrayList<>();
}
// Method to lend a book to the member
public void borrowBook(Book book) {
borrowedBooks.add(book);
}
// Getters
public String getName() {
return name;
}
public String getId() {
return id;
}
public List<Book> getBorrowedBooks() {
return borrowedBooks;
}
// Setters
public void setName(String name) {
this.name = name;
}
public void setId(String id) {
this.id = id;
}
}
Library Class:
import java.util.List;
import java.util.ArrayList;
// Class representing the library
public class Library {
private List<Book> availableBooks;
private List<Member> members;
// Library class constructor
public Library() {
this.availableBooks = new ArrayList<>();
this.members = new ArrayList<>();
}
// Method to add a book to the library
public void addBook(Book book) {
availableBooks.add(book);
}
// Method to register a new member in the library
public void registerMember(Member member) {
members.add(member);
}
// Additional methods to manage loans, returns, etc.
// Getters
public List<Book> getAvailableBooks() {
return availableBooks;
}
public List<Member> getMembers() {
return members;
}
}
In this simple example, we can see how OOP facilitates the management and organization of the system:
-
Encapsulation: Each class (Book, Member, Library) encapsulates its own data and behaviors.
-
Abstraction: Complex operations, such as lending or returning books, are abstracted behind methods.
-
Reuse: Classes can be reused and extended to create more complex systems.
# Conclusions
Applying OOP concepts to build a library system, we have seen how abstraction, encapsulation, and code reuse facilitate the creation of structured and maintainable software.