写一个图书馆管理系统,要求有类的封装,和借用归还功能
时间: 2024-09-18 19:03:54 浏览: 48
设计一个简单的图书馆管理系统,我们可以考虑以下几个关键类:
1. **图书类(Book)**: 封装每本书的基本信息,如书名、作者、ISBN号等,并包含一个借阅状态属性。
```java
public class Book {
private String title;
private String author;
private String isbn;
private boolean isBorrowed;
public Book(String title, String author, String isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
this.isBorrowed = false;
}
// ... getters and setters for properties
public void borrow() {
if (!isBorrowed) {
isBorrowed = true;
System.out.println("Book '" + title + "' has been borrowed.");
} else {
System.out.println("Book is already borrowed.");
}
}
public void returnBook() {
if (isBorrowed) {
isBorrowed = false;
System.out.println("Book '" + title + "' has been returned.");
} else {
System.out.println("Book was not borrowed to begin with.");
}
}
}
```
2. **读者类(Reader)**: 代表一个用户,可以管理他们的借阅记录。
```java
public class Reader {
private String name;
private List<Book> borrowedBooks = new ArrayList<>();
public Reader(String name) {
this.name = name;
}
// ... methods for managing borrowed books
public void borrowBook(Book book) {
book.borrow();
borrowedBooks.add(book);
}
public void returnBook(Book book) {
book.returnBook();
borrowedBooks.remove(book);
}
}
// 图书馆类(Library): 管理书籍和读者
public class Library {
private Map<String, Book> books = new HashMap<>();
public void addBook(Book book) {
books.put(book.getIsbn(), book);
}
// ... methods for handling reader's borrowing and returning
}
```
在这个系统中,`Library`类负责添加书籍,而`Reader`类则负责借阅和归还书籍。每个`Book`对象都有其自身的借阅状态,这体现了类的封装。通过这样的设计,我们实现了基本的借用和归还功能。
阅读全文