通过封装编写Book类。要求:类具有私有属性书名title、页数pageNum、类型type(默认为计算机类),并为这三个属性分别编写set和get方法。其中,页数不能少于200页,否则输出错误信息,并强制赋默认值200;为各属性设置赋值和取值方法;编写方法detail(),用于在控制台输出每本书的书名和页数信息。
public class BookTest {
publicstatic void main(String[] args) {
Bookb1 = new Book("Java入门", 270);
Bookb2 = new Book("北京生活指南", 570, "生活");
b1.detail();
b2.detail();
}
}
public class Book {
private String title; //书名
private int pageNum; //页数
private String type; //图书类型
public Book(String title, int pageNum) {
this.title = title;
this.setPageNum(pageNum);
this.type = "计算机";
}
public Book(String title, int pageNum, String type) {
this.title = title;
this.setPageNum(pageNum);
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
if(pageNum<200) {
System.out.println("页数不能少于200页!");
this.pageNum = 200;
} else {
this.pageNum = pageNum;
}
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void detail() {
System.out.println("书名:" + title + ",页数:" + pageNum);
}
}