设计并实现一个ObjectCounter类,要求:对系统中现存的本类实例计数;每个对象都有唯一的整形ID,按照创建的次序建立;获取当前系统中本类对象的个数;获取每个对象的ID
时间: 2023-12-03 21:42:04 浏览: 72
一个具有对象计数功能的基类
以下是ObjectCounter类的实现,其中使用了静态计数器和静态ID变量:
```java
public class ObjectCounter {
private static int count = 0;
private int id;
public ObjectCounter() {
count++;
id = count;
}
public static int getCount() {
return count;
}
public int getId() {
return id;
}
}
```
使用示例:
```java
ObjectCounter obj1 = new ObjectCounter();
ObjectCounter obj2 = new ObjectCounter();
System.out.println("Number of ObjectCounter objects: " + ObjectCounter.getCount());
System.out.println("obj1 ID: " + obj1.getId());
System.out.println("obj2 ID: " + obj2.getId());
```
输出结果:
```
Number of ObjectCounter objects: 2
obj1 ID: 1
obj2 ID: 2
```
阅读全文