当前位置: 首页 > 图灵资讯 > 技术篇> 继承中构造方法案例

继承中构造方法案例

来源:图灵教育
时间:2023-05-31 09:13:09

/** * 创建一个有姓名和年龄参数的教师类别 * 例如,“名叫张三的30岁老师正在讲课” * 有姓名、有年龄的学生班,三个参数的结果 * 打印出来,比如“李四20岁成绩100分的学生在上课” *////测试类publicccicc class test1 {    public static void main(String[] args) {      teacher t=new teacher(张三),30);      t.teach();      student s=new student(李四,20,100);      s.study();    }}

//父类存储共同参数的名称和年龄public class Person {      private   String name;       private int age;    public Person() {    }    public Person(String name, int age) {        this.name = name;        this.age = age;    }    /**     * 获取     * @return name     */    public String getName() {        return name;    }    /**     * 设置     * @param name     */    public void setName(String name) {        this.name = name;    }    /**     * 获取     * @return age     */    public int getAge() {        return age;    }    /**     * 设置     * @param age     */    public void setAge(int age) {        this.age = age;    }}

///教师子类publicic class teacher extends Person {    public teacher() {    }    public teacher(String name, int age) {        super(name, age);    }    public void teach(){        System.out.println(”姓名为“”+super.getName()+,年龄”        +super.getAge()+“岁老师在讲课”);    }}

////学生子类publicic class student extends Person{    double score;    public student() {    }    public student(String name, int age,double score) {        super(name, age);       this.score=score;    }    public void study(){        System.out.println(”姓名为“”+super.getName()+",年龄"                +super.getAge()+“岁,成绩”+score+“学生正在学习”);    }}