用java编写一个Book类,用于描述个人藏书,包含作者Author、书名Title、价格Price、出版社Publisher、出版年份Published Year五个属性。然后编写一个测试类BookTest,对Book类进行测试,输出正确的属性值。
时间: 2024-11-05 11:27:42 浏览: 20
在Java中,我们可以创建一个名为`Book`的类,它将包含所需的属性,如作者(Author)、书名(Title)、价格(Price)、出版社(Publisher)和出版年份(Published Year)。这里是一个简单的`Book`类的示例:
```java
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;
}
// getter和setter方法
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; }
}
```
接下来,我们创建一个名为`BookTest`的测试类,用于创建一个`Book`实例并打印其属性值:
```java
import org.junit.Test;
public class BookTest {
@Test
public void testBookProperties() {
// 创建一个作者对象
Author author = new Author("John Doe", "johndoe@example.com");
// 创建一个Book对象
Book book = new Book(author, "Harry Potter and the Sorcerer's Stone", 15.99,
"Scholastic Corporation", 1997);
// 测试属性值
System.out.println("Author: " + book.getAuthor().getName());
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());
}
}
// 如果需要,可以为Author单独创建一个类
class Author {
private String name;
private String email;
// 类的其他属性、构造函数、getter和setter
}
```
在这个测试类中,`testBookProperties`方法会打印出指定`Book`实例的各个属性值。运行这个测试类,你应该能看到书的相关信息。
阅读全文