Java语言编程题:声明一个类Person,成员变量有姓名、出生年月、性别、有成员方法以显示姓名、年龄和性别。并测试
时间: 2023-05-13 15:07:46 浏览: 125
Java面向对象程序设计方案练习题.doc
好的,以下是声明一个类Person的Java代码:
```
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() {
LocalDate birthDate = LocalDate.of(birthYear, birthMonth, birthDay);
LocalDate currentDate = LocalDate.now();
return Period.between(birthDate, currentDate).getYears();
}
public String getGender() {
return gender;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + getAge());
System.out.println("Gender: " + gender);
}
}
```
以下是测试代码:
```
public class Main {
public static void main(String[] args) {
Person person = new Person("张三", 1990, 1, 1, "男");
person.displayInfo();
}
}
```
输出结果为:
```
Name: 张三
Age: 31
Gender: 男
```
阅读全文