5.9 声明一个图书类,其数据成员为书名、编号(利用静态变量实现自动编号)、书价,并声明拥有静态变量成员册数、记录图书的总册数,在构造方法中利用静态变量为对象的编号赋值,在主方法中定义对象数组,并求出总册数。
package book;
class Book {
private String name;
private int id;
private float price;
private static int num = 3;
private static int count = 0;
public Book() { // 无参构造函数
count++;
this.id = count;
}
public Book(String name, float price) { // 双参构造函数
this.name = name;
this.price = price;
this.id = (++count);
}
public int getId() { // 获取编号
return this.id;
}
public int getNum() { // 获取数量
return this.num;
}
public void print() { // 显示编号、书名、价格
System.out.println("编号" + getId() + " 书名" + this.name + " 价格" + price);
}
}
public class JiOu {
public static void main(String args[]) {
Book book[] = new Book[3]; // 创建对象数组
book[0] = new Book("数学", 11.1f);
book[1] = new Book("语文", 22.2f);
book[2] = new Book("英语", 33.3f);
for (int i = 0; i < book.length; i++) {
book[i].print();
}
System.out.println("总册数为 " + ((new Book().getId() - 1) * book[2].getNum())); // 输出总册数
}
}
运行结果:
编号1 书名数学 价格11.1
编号2 书名语文 价格22.2
编号3 书名英语 价格33.3
总册数为 9