//限制实例化对象的个数 多个
class Sex {
private String title;
//类内部定义有限个个公共实例化对象,只能通过static方法返回有限对象
private static final Sex MALE = new Sex("男");
private static final Sex FEMALE = new Sex("女");
private Sex(String title) {
this.title = title;
}//构造对象私有化,外界不会随便产生新对象
public String toString() {
return this.title;
}
public static Sex getInstance(int c) {
switch(c) {
case 1 :
return MALE;
case 2 :
return FEMALE;
default :
return null;
}
}
}
public class TestDemo {
public static void main(String args[]) {
Sex s = Sex.getInstance(2);
System.out.println(s);
}
}