(一)根据下面的要求实现人类People
a) 人类People的成员变量:
私有成员name表示姓名,为String类型
私有成员sex表示性别,为boolean类型(true表示男,false表示女)
私有成员age表示年龄,为int类型
b)People类的构造方法(定义完成员方法再定义构造方法)
(1)无参的构造方法People(),将各成员变量初始化为默认值
(2)People(String name,boolean sex,int age)分别对姓名、性别、年龄进行初始化
(3)People(String name,boolean sex)分别对姓名、性别进行初始化
(4)People(String name,int age)分别对姓名、年龄进行初始化
c) 人类People的成员方法:
(1)设置姓名的公有方法setName()
(2)读取姓名的公有方法getName()
(3)设置性别的公有方法setSex()
(4)读取性别的公有方法public String getSex( )
如果sex为true,返回字符串”male”,否则返回字符串”female”
(5)设置年龄的公有方法setAge()
(6)读取年龄的公有方法getAge()
(7)void disp( ) 将人的姓名、性别、年龄输出到屏幕
(二)建立类People的测试类,创建2个对象并分别设置对象的姓名、性别、年龄,然后输出该人的基本信息。
public class People {
private String name;//姓名
private boolean sex;//性别
private int age;//年龄
public People(){
}
public People(String name,boolean sex,int age){
//this.name=name;
this.setName(name);
this.setSex(sex);
this.setAge(age);
}
public People(String name){
//setName(name);
this(name,false,0);
}
public People(boolean sex){
setSex(sex);
}
public People(int age){
setAge(age);
}
public People(String name,boolean sex){
//this.setName(name);
//this.setSex(sex);
this(name,sex,0);
}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
//在Eclipse中set和get方法可以自动生成
public String getSex() {
if(sex==true){
return "male";
}else{
return "female";
}
}
public void setSex(boolean sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age>0){
this.age = age;
}
}
public void disp(){
System.out.println("姓名:"+this.getName()+" 性别:"+this.getSex()+" 年龄:"+getAge());
}
}
<span style="color:#ff0000;">public class PeopleTest {
/**
* @param args
*/
public static void main(String[] args) {
People people1=new People();
people1.disp();
people1.setName("张三");
people1.setSex(true);
people1.setAge(20);
people1.disp();
People people2;
people2=new People("李四",true,18);
people2.disp();
People people3=new People("王五");
people3.disp();
}
}</span>