代码如下:

// 父类 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);
    }
}

输出结果:

我承诺,我会好好学习。
我承诺,我会认真教学。
Tom爱玩足球
Alice爱玩象棋
``
①做一个Student类Student类有名称name性别sex年龄age学号stu_id做合理封装通过构造器在创建对象时将4个属性赋值。②写一个Teacher类Teacher类有名称name性别sex年龄age工龄work_age做合理封装通过构造器在创建对象时将4个属性赋值。③因为Student类和Teacher类有公共内容所以尝试编写父类Person将公共内容抽象成父类。④学生需要有学习的方

原文地址: http://www.cveoy.top/t/topic/ibVK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录