第4章-类与对象-实验2学校与教师





问题描述:
模拟学校和教师的关系,学校有不同学科的老师,不同学科的老师上课的授课方式不同。
代码:


Test.java

public class Test {
    public static void main(String[]args){
        Teacher zhang,wang;
        zhang=new Teacher();
        wang=new Teacher();
        zhang.teacherType=1;
        wang.teacherType=2;
        School middleschool=new School();
        middleschool.setTeacher(zhang,wang);
        middleschool.startMathLesson();
        middleschool.startMusicLesson();
  
    }
}


School.java

public class School {
    Teacher mathTeacher,musicTeacher;
    void setTeacher(Teacher t1,Teacher t2){
        mathTeacher=t1;
        musicTeacher=t2;
    }
    void startMathLesson(){
        mathTeacher.speak();
    }
    void startMusicLesson(){
        musicTeacher.speak();
    }
}


Teacher.java

public class Teacher {
    int teacherType;
    public void speak(){
        if(teacherType==1){
            System.out.println("The topic of this class"
                    + "is Math.");
            
        }
        else if(teacherType==2){
            System.out.println("The topic of this class"
                    + "is Music.");
            
        } 
    }
}



运行结果:

第4章-类与对象-实验2学校与教师_第1张图片


第4章-类与对象-实验2学校与教师_第2张图片




总结:掌握对象的组合及参数的传递


你可能感兴趣的:(JAVA)