定义一个教师类,要求一:定义三个教师对象,添加到集合ArrayList,遍历输出
时间: 2024-03-12 13:49:48 浏览: 73
以下是定义教师类并添加到ArrayList并遍历输出的示例代码:
```java
import java.util.ArrayList;
public class Teacher {
private String name;
private int age;
private String subject;
public Teacher(String name, int age, String subject) {
this.name = name;
this.age = age;
this.subject = subject;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getSubject() {
return subject;
}
public static void main(String[] args) {
ArrayList<Teacher> teacherList = new ArrayList<>();
// 创建三个教师对象并添加到ArrayList
Teacher teacher1 = new Teacher("张三", 30, "数学");
Teacher teacher2 = new Teacher("李四", 35, "英语");
Teacher teacher3 = new Teacher("王五", 40, "物理");
teacherList.add(teacher1);
teacherList.add(teacher2);
teacherList.add(teacher3);
// 遍历输出ArrayList中的教师对象
for (Teacher teacher : teacherList) {
System.out.println("教师姓名:" + teacher.getName() + ",教师年龄:" + teacher.getAge() + ",教授学科:" + teacher.getSubject());
}
}
}
```
运行结果:
```
教师姓名:张三,教师年龄:30,教授学科:数学
教师姓名:李四,教师年龄:35,教授学科:英语
教师姓名:王五,教师年龄:40,教授学科:物理
```
阅读全文