Java面向对象编程实战:模拟学校管理系统(含代码示例)
// 父类 Person public class Person { private String name; private String sex; private int age;
public Person(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public int getAge() {
return age;
}
public String play() {
return "";
}
}
// 子类 Student public class Student extends Person { private int stuId;
public Student(String name, String sex, int age, int stuId) {
super(name, sex, age);
this.stuId = stuId;
}
public int getStuId() {
return stuId;
}
public void study() {
System.out.println("我承诺,我会好好学习。");
}
@Override
public String play() {
return getName() + "爱玩足球";
}
}
// 子类 Teacher public class Teacher extends Person { private int workAge;
public Teacher(String name, String sex, int age, int workAge) {
super(name, sex, age);
this.workAge = workAge;
}
public int getWorkAge() {
return workAge;
}
public void teach() {
System.out.println("我承诺,我会认真教学。");
}
@Override
public String play() {
return getName() + "爱玩象棋";
}
}
// 学校类 School public class School { public void manager(Person person) { if (person instanceof Teacher) { Teacher teacher = (Teacher) person; System.out.println(teacher.play()); } else if (person instanceof Student) { Student student = (Student) person; System.out.println(student.play()); } } }
// 测试类 public class Main { public static void main(String[] args) { Student student = new Student("Tom", "Male", 18, 2021001); Teacher teacher = new Teacher("Alice", "Female", 30, 5);
student.study();
teacher.teach();
School school = new School();
school.manager(student);
school.manager(teacher);
}
}
原文地址: https://www.cveoy.top/t/topic/pUDa 著作权归作者所有。请勿转载和采集!