课后习题 Java设计person类,有姓名,年龄,性别。要求:该类至多只能创建一男,一女两个对象。
package com.liuyanzhao;
class Person {
private static int c=0,c1=0;
private String name;
private int age;
private String sex;
public int getAge() {
return age;
}
public String getSex() {
return sex;
}
public String getName() {
return name;
}
private Person(String name,int age,String sex) {
this.name = name;
this.age = age;
this.sex = sex;
if(sex.equals("男")) {
c++;
} else if(sex.equals("女")) {
c1++;
}
}
public static Person create(String name,int age,String sex) {
if(sex.equals("男")) {
if(c==1) {
System.out.println("创建失败:已经创建了一个男性对象啦");
return null;
}
} else if(sex.equals("女")) {
if(c1==1) {
System.out.println("创建失败:已经创建了一个女性对象啦");
return null;
}
}
System.out.println("创建成功:"+"name="+name+",age="+age+",sex="+sex);
return new Person(name,age,sex);
}
}
public class Test1 {
public static void main(String[] args) {
Person p = Person.create("刘言曌",20,"男");
Person p1 = Person.create("刘䶮曌",19, "男");
Person p2 = Person.create("刘亦菲", 30, "女");
Person p3 = Person.create("刘惜君", 29, "女");
}
}
运行结果:
如果有其他的方法,大几不妨也贴出来分享交流
本文地址:http://liuyanzhao.com/3336.html
转载请注明