编写一个Java应用程序,模拟学校和教师的关系,即学校将教师作为自己的一个成员变量,具体要求如下: (1)有3个源文件:School.java、Teacher.java和MainClass.java,其中Teacher.java中的Teacher类负责设计“教师”类。成员有:teacherType,表示老师的类型,取值为1代表数学老师,取值为0代表音乐老师。设置教师类型的方法void setTeacherType(int type),给teacherType设置值。授课的方法public void speak( ),判断老师如果是数学老师就输出“课程的内容是二次方程”。如果是音乐老师就输出“课程的内容是学唱五线谱”。 (2)School.java中的School类负责设计“学校”类,School有类型是Teacher、名字是mathTeacher和musicTeacher的成员变量。 有setTeacher方法,通过参数给mathTeacher和musicTeacher设置值。有startMathLesson方法,让mathTeacher执行speak( )方法,有startMusicLesson方法,让musicTeacher执行speak( )方法。 (3)MainClass.java中含有主类,创建教师对象和学校对象,进行测试。 要求:写出实验程序和实验输出结果。
时间: 2024-02-27 11:55:24 浏览: 101
以下是符合要求的Java程序:
Teacher.java
```
public class Teacher {
private int teacherType;
public void setTeacherType(int type) {
teacherType = type;
}
public void speak() {
if (teacherType == 1) {
System.out.println("课程的内容是二次方程");
} else if (teacherType == 0) {
System.out.println("课程的内容是学唱五线谱");
}
}
}
```
School.java
```
public class School {
private Teacher mathTeacher;
private Teacher musicTeacher;
public void setTeacher(Teacher math, Teacher music) {
mathTeacher = math;
musicTeacher = music;
}
public void startMathLesson() {
mathTeacher.speak();
}
public void startMusicLesson() {
musicTeacher.speak();
}
}
```
MainClass.java
```
public class MainClass {
public static void main(String[] args) {
Teacher mathTeacher = new Teacher();
mathTeacher.setTeacherType(1);
Teacher musicTeacher = new Teacher();
musicTeacher.setTeacherType(0);
School school = new School();
school.setTeacher(mathTeacher, musicTeacher);
school.startMathLesson();
school.startMusicLesson();
}
}
```
输出结果:
```
课程的内容是二次方程
课程的内容是学唱五线谱
```
阅读全文