编写PersonInfo类,包含姓名,性别,出生年月,个人爱好,采用set注入实现属性值的注入并在程序中显示所以属性的值
时间: 2024-12-17 15:52:20 浏览: 2
在Java中,你可以创建一个名为`PersonInfo`的类,用于存储个人信息。这里是一个简单的例子:
```java
public class PersonInfo {
// 定义属性并设置setter方法
private String name;
private String gender;
private LocalDate birthDate; // 使用Java 8的LocalDate代替传统的String表示日期
private List<String> hobbies;
// 构造函数接受所有属性作为参数
public PersonInfo(String name, String gender, LocalDate birthDate, List<String> hobbies) {
this.name = name;
this.gender = gender;
this.birthDate = birthDate;
this.hobbies = hobbies;
}
// 提供setter方法以便注入属性值
public void setName(String name) { this.name = name; }
public void setGender(String gender) { this.gender = gender; }
public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; }
public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; }
// 获取属性值的方法
public String getName() { return name; }
public String getGender() { return gender; }
public LocalDate getBirthDate() { return birthDate; }
public List<String> getHobbies() { return hobbies; }
// 显示所有属性的值
@Override
public String toString() {
return "Name: " + name +
", Gender: " + gender +
", Birth Date: " + birthDate +
", Hobbies: " + hobbies;
}
}
// 程序中如何使用这个类展示属性值
public static void main(String[] args) {
List<String> hobbies = Arrays.asList("Reading", "Swimming", "Cooking");
PersonInfo person = new PersonInfo("John Doe", "Male", LocalDate.of(1990, 5, 1), hobbies);
System.out.println(person); // 输出:Name: John Doe, Gender: Male, Birth Date: 1990-05-01, Hobbies: [Reading, Swimming, Cooking]
}
```
在这个例子中,我们通过构造函数接收初始值,并提供对应的setter方法允许外部系统动态地注入属性值。`toString()`方法被重写,用于方便地显示所有属性信息。
阅读全文