用Java编写定义一个Teacher类,有姓名和学科2个属性,之后创建3个teacher对象并赋值,然后存入集合中,用曾强for遍历集合,控制台打印每个老师的信息
时间: 2024-04-12 18:31:44 浏览: 126
好的,下面是用Java编写的Teacher类的示例代码:
```java
public class Teacher {
private String name;
private String subject;
public Teacher(String name, String subject) {
this.name = name;
this.subject = subject;
}
public String getName() {
return name;
}
public String getSubject() {
return subject;
}
}
```
接下来,我们可以创建三个Teacher对象,并将它们存入集合中,使用增强for循环遍历集合,并打印每个老师的信息。下面是示例代码:
```java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Teacher> teachers = new ArrayList<>();
Teacher teacher1 = new Teacher("Alice", "Math");
Teacher teacher2 = new Teacher("Bob", "English");
Teacher teacher3 = new Teacher("Charlie", "Science");
teachers.add(teacher1);
teachers.add(teacher2);
teachers.add(teacher3);
for (Teacher teacher : teachers) {
System.out.println("Name: " + teacher.getName());
System.out.println("Subject: " + teacher.getSubject());
System.out.println();
}
}
}
```
运行上述代码,将会输出每个老师的姓名和学科信息。例如:
```
Name: Alice
Subject: Math
Name: Bob
Subject: English
Name: Charlie
Subject: Science
```
希望这个示例能够帮到你!如果还有其他问题,请随时提问。
阅读全文