设计一个library类,它包含一个内部类Book,Book类有书名,作者和出版年份的属性.library类应该有一个方法打印所有书籍的信息
时间: 2024-10-12 17:11:20 浏览: 48
library-book-scanner:使用我们学校的二维码进行简单的图书管理
设计一个名为`Library`的类,它包含一个内部类`Book`作为它的组成部分。`Book`类将拥有三个私有属性:`title`(书名)、`author`(作者)和`yearOfPublication`(出版年份)。为了提供访问和操作这些信息的功能,我们需要在`Book`类中定义getter和setter方法,以及一个代表书籍内容的构造函数。
```java
public class Library {
// 内部类Book
private class Book {
private String title;
private String author;
private int yearOfPublication;
public Book(String title, String author, int year) {
this.title = title;
this.author = author;
this.yearOfPublication = year;
}
// getter和setter方法
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYearOfPublication() {
return yearOfPublication;
}
public void setYearOfPublication(int yearOfPublication) {
this.yearOfPublication = yearOfPublication;
}
}
// Library类的方法来管理图书
public void printBooks(Book[] books) {
for (Book book : books) {
System.out.println("书名: " + book.getTitle());
System.out.println("作者: " + book.getAuthor());
System.out.println("出版年份: " + book.getYearOfPublication());
System.out.println("--------------------");
}
}
}
// 使用示例
public static void main(String[] args) {
Library library = new Library();
Book book1 = library.new Book("Java编程思想", "Bruce Eckel", 2004);
Book book2 = library.new Book("深入浅出Python", "Mark Lutz", 2015);
Book[] books = {book1, book2};
library.printBooks(books);
}
```
阅读全文