[1]声明图书类,该类包含一个静态变量,作用为记录图书总册数;该类还包含的数据成员有书名、编号(利用静态变量实现从1开始的自动编号)、书价;在构造方法中,利用静态变量为对象的编号赋值。 [2]构造测试类对上述图书类进行测试
时间: 2023-06-27 20:05:59 浏览: 154
使用静态工厂实例化;使用IOC容器实例化上述类,并对属性使用构造方法注入并测试;模拟三层体系结构实现对部门项目的查询、添加和修改
[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` 的值,来验证自动编号的功能。
阅读全文