定义一个Student类,并要求其他类在使用Student类的时候,最多只能创建10个Student类的对象
1、私有化构造方法
2、只能在内部创建,并返回该对象(通过Student类内部的方法)
需要一个计数器count指示当前类创建了多少次对象(count必须是类所有,全体对象共享)
public class Test {
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
Student.createNew();
}
}
}
class Student {
private Student() {
}
static int i = 1;
public static Student createNew() {
if (i <= 10) {
System.out.println("你的第" + i + "个Student对象");
Student student = new Student();
i++;
return student;
} else {
System.out.println("创建对象失败,最多只能创建10个Student类的对象。");
return null;
}
}
}