Java编程题:声明一个类Person,成员变量有姓名、出生年月、性别、有成员方法以显示姓名、年龄和性别。
时间: 2023-05-13 19:07:43 浏览: 148
好的,这是一个简单的Java编程题,声明一个Person类,包含姓名、出生年月、性别三个成员变量,以及一个显示姓名、年龄和性别的成员方法。以下是代码示例:
public class Person {
private String name;
private int birthYear;
private int birthMonth;
private int birthDay;
private String gender;
public Person(String name, int birthYear, int birthMonth, int birthDay, String gender) {
this.name = name;
this.birthYear = birthYear;
this.birthMonth = birthMonth;
this.birthDay = birthDay;
this.gender = gender;
}
public String getName() {
return name;
}
public int getAge() {
Calendar cal = Calendar.getInstance();
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayNow = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - birthYear;
if (birthMonth > monthNow || (birthMonth == monthNow && birthDay > dayNow)) {
age--;
}
return age;
}
public String getGender() {
return gender;
}
public void displayInfo() {
System.out.println("姓名:" + name);
System.out.println("年龄:" + getAge());
System.out.println("性别:" + gender);
}
}
在这个Person类中,我们定义了一个构造函数,用于初始化成员变量;getName、getAge、getGender三个方法用于获取姓名、年龄和性别;displayInfo方法用于显示姓名、年龄和性别。
阅读全文