2.编写一个Book类,用于描述个人藏书,包含作者 Author、书名 Title、价格Price、出版社 Publisher、出版年份Published Year 共5个属性。然后编写一个测试类 BookTest,对Book类进行测试,输出正确的属性值。
时间: 2024-12-07 19:19:18 浏览: 12
首先,我们来创建一个名为`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;
}
// getter和setter方法
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;
}
}
// 现在创建一个测试类BookTest来验证Book类
public class BookTest {
public static void main(String[] args) {
// 创建一个Book对象
Book book = new Book("J.K.罗琳", "哈利·波特与魔法石", 200, " Bloomsbury Publishing", 1997);
// 输出属性值
System.out.println("作者: " + book.getAuthor());
System.out.println("书名: " + book.getTitle());
System.out.println("价格: " + book.getPrice());
System.out.println("出版社: " + book.getPublisher());
System.out.println("出版年份: " + book.getPublishedYear());
// 测试用完后记得清理资源或关闭连接等
}
}
```
在这个测试类中,我们创建了一个`Book`对象,并通过getter方法获取并打印每个属性的值。
阅读全文