帮我写一个用java实现根据出生日期计算年龄并进行pojo封装
时间: 2024-05-08 18:22:22 浏览: 161
好的,以下是代码实现:
```java
import java.time.LocalDate;
import java.time.Period;
public class AgeCalculator {
private int age;
private LocalDate birthDate;
public AgeCalculator(LocalDate birthDate) {
this.birthDate = birthDate;
this.age = calculateAge();
}
private int calculateAge() {
LocalDate currentDate = LocalDate.now();
return Period.between(birthDate, currentDate).getYears();
}
// Getters and setters
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
}
```
使用示例:
```java
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate birthDate = LocalDate.of(2000, 10, 10);
AgeCalculator ageCalculator = new AgeCalculator(birthDate);
System.out.println(ageCalculator.getAge()); // 输出:21
}
}
```
以上就是根据出生日期计算年龄并进行pojo封装的Java实现。
阅读全文