Java编写一个 Book 类,用于描述个人藏书,包含作者 Author、书名 Tile、价格 Price、出版社 Publisher、出版年份 Published Year共5个属性。然后编写一个测试,输出正确的属性值
时间: 2024-10-23 09:04:30 浏览: 35
好的,我们可以创建一个名为`Book`的简单Java类,用于表示书籍信息。首先,我们定义一个`Author`类作为`Book`的一个内部类,代表作者。然后我们将创建`Book`类并设置其属性。
```java
// 定义作者类
class Author {
private String name;
public Author(String name) {
this.name = name;
}
// Getters and setters省略,这里仅展示构造函数
public String getName() {
return name;
}
}
// 定义Book类
public class Book {
private Author author;
private String title;
private double price;
private String publisher;
private int publishedYear;
public Book(Author author, String title, double price, String publisher, int publishedYear) {
this.author = author;
this.title = title;
this.price = price;
this.publisher = publisher;
this.publishedYear = publishedYear;
}
// 获取和设置属性的方法
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public int getPublishedYear() {
return publishedYear;
}
public void setPublishedYear(int publishedYear) {
this.publishedYear = publishedYear;
}
@Override
public String toString() {
return "Book{" +
"author=" + author.getName() +
", title='" + title + '\'' +
", price=" + price +
", publisher='" + publisher + '\'' +
", publishedYear=" + publishedYear +
'}';
}
}
// 测试类
public class BookTest {
public static void main(String[] args) {
// 创建一个作者实例
Author author = new Author("张三");
// 创建一本书实例
Book book = new Book(author, "Java编程入门", 49.0, "人民邮电出版社", 2021);
// 输出书籍属性值
System.out.println("Book details:");
System.out.println(book);
}
}
```
当你运行`BookTest`的`main`方法时,它将输出类似下面的信息:
```
Book details:
Book{author=张三, title='Java编程入门', price=49.0, publisher='人民邮电出版社', publishedYear=2021}
```
阅读全文