2、 定义一个Teacher类,包含姓名,性别,定义它的带2个参数的构造方法和get及set方法,并重写toSting方法用于输出姓名和性别。使用List接口创建集合对象用于保存5位教师信息(向集合中添加元素),显示所有的教师的信息(姓名、性别)。
时间: 2024-03-06 10:49:23 浏览: 67
好的,我来解答你的问题。
以下是定义的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 "Teacher{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
```
以下是使用List接口创建集合对象并保存5位教师信息的代码:
```java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
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("钱七", "男"));
// 显示所有教师信息
for (Teacher teacher : teacherList) {
System.out.println(teacher.toString());
}
}
}
```
输出结果:
```
Teacher{name='张三', gender='男'}
Teacher{name='李四', gender='女'}
Teacher{name='王五', gender='男'}
Teacher{name='赵六', gender='女'}
Teacher{name='钱七', gender='男'}
```
希望我的回答能对你有所帮助!
阅读全文