用JAVA声明一个类person,成员变量变量有姓名、出生年月、性别、有成员方法以显示姓名年龄和性别
时间: 2023-05-12 12:07:49 浏览: 105
好的,以下是用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 getBirthYear() {
return birthYear;
}
public int getBirthMonth() {
return birthMonth;
}
public int getBirthDay() {
return birthDay;
}
public String getGender() {
return gender;
}
public void displayInfo() {
int age = calculateAge();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gender: " + gender);
}
private int calculateAge() {
LocalDate birthdate = LocalDate.of(birthYear, birthMonth, birthDay);
LocalDate now = LocalDate.now();
return Period.between(birthdate, now).getYears();
}
}
```
这个类有五个成员变量:姓名、出生年月、性别。它还有一个构造函数,用于初始化这些成员变量。它还有一个名为displayInfo的成员方法,用于显示姓名、年龄和性别。这个类还有一个私有方法calculateAge,用于计算年龄。