Java 编写一个Book类,用于描述个人藏书,包含作者Author、书名Title、价格Price、出版社Publisher、出版年份Published Year五个属性。然后编写一个测试类BookTest,对Book类进行测试,输出正确的属性值
时间: 2024-12-19 13:22:46 浏览: 19
在Java中,你可以创建一个`Book`类来描述个人藏书的基本信息。首先,我们定义`Book`类:
```java
public class Book {
private String author;
private String title;
private double price;
private String publisher;
private int publishedYear;
// 构造函数
public Book(String 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 String getAuthor() {
return author;
}
public void setAuthor(String 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 + '\'' +
", title='" + title + '\'' +
", price=" + price +
", publisher='" + publisher + '\'' +
", publishedYear=" + publishedYear +
'}';
}
}
```
接下来,我们可以创建一个`BookTest`类来进行测试:
```java
import org.junit.Test;
public class BookTest {
@Test
public void testBookProperties() {
// 创建一个Book对象
Book book = new Book("作者A", "书名B", 50.0, "出版社C", 2022);
// 测试属性值
System.out.println("Author: " + book.getAuthor());
System.out.println("Title: " + book.getTitle());
System.out.println("Price: " + book.getPrice());
System.out.println("Publisher: " + book.getPublisher());
System.out.println("Published Year: " + book.getPublishedYear());
// 输出完整书的信息
System.out.println(book);
}
}
```
在这个测试类中,我们创建了一个`Book`实例,并通过`get`方法检查每个属性的值。`toString`方法则被用来展示整个书籍对象的详细信息。
阅读全文