[1]声明图书类,该类包含一个静态变量,作用为记录图书总册数;该类还包含的数据成员有书名、编号(利用静态变量实现从1开始的自动编号)、书价;在构造方法中,利用静态变量为对象的编号赋值。 [2]构造测试类对上述图书类进行测试
时间: 2023-06-27 11:05:59 浏览: 161
[1]下面是图书类的代码实现:
```java
public class Book {
private static int totalBooks = 0;
private String title;
private int id;
private double price;
public Book(String title, double price) {
this.title = title;
this.id = ++totalBooks;
this.price = price;
}
public String getTitle() {
return title;
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
public static int getTotalBooks() {
return totalBooks;
}
}
```
[2]下面是测试类的代码实现:
```java
public class TestBook {
public static void main(String[] args) {
Book book1 = new Book("Java Programming", 99.9);
Book book2 = new Book("Python Programming", 88.8);
System.out.println("Total books: " + Book.getTotalBooks());
System.out.println("Book 1 - Title: " + book1.getTitle() + ", ID: " + book1.getId() + ", Price: " + book1.getPrice());
System.out.println("Book 2 - Title: " + book2.getTitle() + ", ID: " + book2.getId() + ", Price: " + book2.getPrice());
}
}
```
在测试类中,我们创建了两个 `Book` 对象,分别是 `book1` 和 `book2`,并输出了它们的属性值。同时,我们也输出了静态变量 `totalBooks` 的值,来验证自动编号的功能。
阅读全文