0
点赞
收藏
分享

微信扫一扫

继承中构造方法案例

/**
 * 创建一个教师类,有姓名和年龄两个参数
 * 打印出比如“姓名为张三年龄30岁的老师正在讲课”
 * 创建一个学生类,有姓名,年龄,成绩三个参数
 * 打印出比如“姓名为李四年龄20岁成绩100分的学生正在上课”
 */
//测试类
public 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;
    }

}

//教师子类
public 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()+"岁的老师正在讲课");
    }
}

//学生子类
public 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+"分的学生正在学习");
    }
}


举报

相关推荐

0 条评论