java—限制使用带参数的构造函数创建的示例数

3ks5zfa0  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(433)

如何使我的程序将下面的示例创建限制为4个,以便当我尝试创建第五个学校时,它会显示一条错误消息,“学校无法注册,已达到最大值”。一如既往地谢谢你

public class Driver {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Header h1 = new Header();
        h1.schoolHeader();
        School s1 = new School("Pascoe Vale High School", "101");
        School s2 = new School("North Melbourne Primary School", "102");
        School s3 = new School("St Aloysuis College", "103");
        School s4 = new School("Coburg High School", "104");
        School s5 = new School("Chuka Nwobi High School", "105");
    }
}
class School {
    public static int objCount = 0;
    private static String regId;
    private String name;

    School(String name, String regId) {
        this.name = name;
        this.regId = regId;
        System.out.println("***Successfully registered " + getName());
        objCount++;
    }

    public void registerHeader() {
        System.out.println("--- Registering Participating Schools---");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRegId() {
        return regId;
    }
    public void setRegId(String regId) {
        this.regId = regId;
    }
}
nlejzf6q

nlejzf6q1#

您要求的示例代码:

static final int ALLOWED_COUNT = 4;

public School(String name, String regId) {
    if (objCount >= ALLOWED_COUNT) {
        throw new TooManySchoolsException("Only " + ALLOWED_COUNT + " schools allowed!");
    }
    this.name = name;
    this.regId = regId;
    System.out.println("***Successfully registered " + getName());
    objCount++;
}

老实说,这样做不是个好主意。最好允许创建无限数量的学校对象,并有一个单独的schoolregistry类来跟踪注册的学校数量。

class SchoolRegistry {
    static final int MAX_SCHOOLS = 4;
    private List<School> schools = new ArrayList<>();
    public void register(School s) {
        if (schools.size() > MAX_SCHOOLS) throw new TooManySchoolsException();
        schools.add(s);
    }
}

相关问题