2、 定义一个Teacher类,包含姓名,性别,定义它的带2个参数的构造方法和get及set方法,并重写toSting方法用于输出姓名和性别。使用List接口创建集合对象用于保存5位教师信息(向集合中添加元素),显示所有性别为“
时间: 2024-03-06 20:48:47 浏览: 123
在Java中,可以这样定义一个Teacher类:
```java
public class Teacher {
private String name;
private String gender;
public Teacher(String name, String gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Name: " + name + ", Gender: " + gender;
}
}
```
然后,使用List接口创建集合对象,并向集合中添加元素:
```java
List<Teacher> teacherList = new ArrayList<>();
teacherList.add(new Teacher("张三", "男"));
teacherList.add(new Teacher("李四", "女"));
teacherList.add(new Teacher("王五", "男"));
teacherList.add(new Teacher("赵六", "女"));
teacherList.add(new Teacher("钱七", "男"));
```
最后,显示所有性别为“女”的教师信息:
```java
for (Teacher teacher : teacherList) {
if (teacher.getGender().equals("女")) {
System.out.println(teacher);
}
}
```
阅读全文