class CountClass{
static public int sum=0;
private CountClass(){
}
static public CountClass getCountClass(){
if(CountClass.sum>2) {
System.out.println("对象实例超过3!");
return null;
}
else {
CountClass.sum++;
return new CountClass();
}
}
static public void main(String[] str){
CountClass s1=CountClass.getCountClass();
System.out.println(CountClass.sum+" "+s1);
CountClass s2=CountClass.getCountClass();
System.out.println(CountClass.sum+" "+s2);
CountClass s3=CountClass.getCountClass();
System.out.println(CountClass.sum+" "+s3);
CountClass s4=CountClass.getCountClass();
System.out.println(CountClass.sum+" "+s4);
}
}
public class Text {
static int instanceCount = 0;
Text() {
instanceCount++;
if(instanceCount > 3) {
try {
throw new TextException();
} catch(Exception e) {
System.out.println("这个类已经实例化超过3次");
}
}
}
public static void main(String args[]) {
Text t = new Text();
Text t1 = new Text();
Text t2 = new Text();
}
}
class TextException extends Exception {}
把那个类的一个变量设置成static的就行 然后在里面写个
public static int i=0;
i++
if(i>3){
System.out.println("err");
break;
}