将book与booktest分成两个类
时间: 2024-10-27 10:13:30 浏览: 13
类与对象的PPT
将`Book`和`BookTest`分别放在两个独立的类中可以使代码更清晰、易于维护。以下是两个类的分离版本:
**Book.java**
```java
public class Book {
private String title;
private int pageNum = 200;
public Book(String title) {
if (title == null || title.isEmpty()) {
throw new IllegalArgumentException("Book title cannot be empty");
}
this.title = title;
}
// getter and setter methods
public String getTitle() {
return title;
}
public void setTitle(String title) {
if (title == null || title.isEmpty()) {
throw new IllegalArgumentException("Book title cannot be empty");
}
this.title = title;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
if (pageNum < 200) {
System.out.println("Error: Page number should not be less than 200. Setting default to 200.");
this.pageNum = 200;
} else {
this.pageNum = pageNum;
}
}
// detail method
public void detail() {
System.out.println("Title: " + title + ", Pages: " + pageNum);
}
}
```
**BookTest.java**
```java
import org.junit.Test;
public class BookTest {
@Test
public void testBook() {
// 创建Book对象并调用detail方法
Book book = new Book("Java Programming");
book.detail();
// 修改页数并验证
try {
book.setPageNum(150); // 尝试设置无效页数
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
// 再次调用detail方法
book.detail();
}
}
```
现在,`Book`类专注于书籍实体的定义,而`BookTest`类则是一个JUnit测试类,用于测试`Book`类的行为。这样的设计使得每个类都有明确的责任,提高了代码的复用性和可测试性。
阅读全文