用java声明一个学生类,包括name、sex、birthday;showStudent()可以打印学生的姓名、性别和实际周岁年龄
时间: 2024-04-29 20:23:47 浏览: 106
以下是Java代码:
```
import java.time.LocalDate;
import java.time.Period;
public class Student {
private String name;
private String sex;
private LocalDate birthday;
// 构造方法
public Student(String name, String sex, LocalDate birthday) {
this.name = name;
this.sex = sex;
this.birthday = birthday;
}
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
// 计算年龄的方法
public int getAge() {
LocalDate today = LocalDate.now();
Period age = Period.between(birthday, today);
return age.getYears();
}
// 打印学生信息的方法
public void showStudent() {
System.out.println("姓名:" + name);
System.out.println("性别:" + sex);
System.out.println("年龄:" + getAge() + "岁");
}
}
```
阅读全文