我怎樣才能使我的程序限制以下實例創建四個這樣,當我嘗試創建第五中學是顯示錯誤消息的實例的數量,「學校無法註冊達到最大值「。 感謝一如既往限制創建使用帶有參數的構造函數
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;
}
}
介紹工廠模式。 – Flown
使用數組和全球個性化......或者在學校靜態counteer –
那麼你已經在你的構造函數中的靜態學校計數器,拋出一個異常,如果正在創建一個又一個? – daniu