Java基础编程题目——编写Teacher类和Student类继承Person类

定义一个Person类,含姓名、性别、年龄、年龄等字段;继承Person类设计Teacher类,增加职称、部门等字段;继承Person类设计Student类,增加学号、入学时间、专业等字段。定义各类的构造方法和toString()方法,并分别创建对象进行测试。

public class Persons {
    public static void main(String[] args) {
        Teacher A = new Teacher("张三", "男", 35, "教授", "教学");
        Student B = new Student("李四", "男", 20, 123, 201809, "computer");
        System.out.println(A.toString());
        System.out.println(B.toString());
    }
}

class Person {
    private String name;
    private String sex;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

class Teacher extends Person {
    String zhicheng;
    String bumen;

    public Teacher(String name, String sex, int age, String zhicheng, String bumen) {
        this.setName(name);
        this.setSex(sex);
        this.setAge(age);
        this.zhicheng = zhicheng;
        this.bumen = bumen;
    }

    public String toString() {
        return "姓名:" + this.getName() +
                ",性别:" + this.getSex() +
                ",年龄:" + this.getAge() +
                ",职称:" + this.zhicheng +
                ",部门:" + this.bumen;
    }
}

class Student extends Person {
    int num;
    int time;
    String zhuanye;

    public Student(String name, String sex, int age, int num, int time, String zhuanye) {
        this.setName(name);
        this.setSex(sex);
        this.setAge(age);
        this.num = num;
        this.time = time;
        this.zhuanye = zhuanye;
    }

    public String toString() {
        return "姓名:" + this.getName() +
                ",性别:" + this.getSex() +
                ",年龄:" + this.getAge() +
                ",学号:" + this.num +
                ",入学时间:" + this.time +
                ",专业:" + this.zhuanye;
    }
}
发布了203 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43479432/article/details/105096392