创建一个Book类,包含title、author和publisher属性,并编写对应的构造方法和访问方法。然后创建一个Library类,包含name和books属性,其中books属性是一个存储Book对象的数组。在Library类中编写一个方法addBook(Book book),用于向图书馆添加书籍。在main方法中创建一个Library对象,并添加一些书籍,然后打印出图书馆的名称和书籍列表。
时间: 2024-02-06 12:09:58 浏览: 120
javaScript对象和属性的创建方法
下面是符合要求的代码实现:
```
public class Book {
private String title;
private String author;
private String publisher;
public Book(String title, String author, String publisher) {
this.title = title;
this.author = author;
this.publisher = publisher;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublisher() {
return publisher;
}
}
public class Library {
private String name;
private Book[] books;
public Library(String name, int size) {
this.name = name;
this.books = new Book[size];
}
public void addBook(Book book) {
for (int i = 0; i < books.length; i++) {
if (books[i] == null) {
books[i] = book;
break;
}
}
}
public void printBooks() {
System.out.println("Books in " + name + ":");
for (Book book : books) {
if (book != null) {
System.out.println(book.getTitle() + " by " + book.getAuthor() + ", published by " + book.getPublisher());
}
}
}
}
public class Main {
public static void main(String[] args) {
Library library = new Library("Central Library", 5);
library.addBook(new Book("To Kill a Mockingbird", "Harper Lee", "J. B. Lippincott & Co."));
library.addBook(new Book("1984", "George Orwell", "Secker & Warburg"));
library.addBook(new Book("Pride and Prejudice", "Jane Austen", "T. Egerton, Whitehall"));
library.printBooks();
}
}
```
输出结果:
```
Books in Central Library:
To Kill a Mockingbird by Harper Lee, published by J. B. Lippincott & Co.
1984 by George Orwell, published by Secker & Warburg
Pride and Prejudice by Jane Austen, published by T. Egerton, Whitehall
```
阅读全文