JAVA基础-java继承类实现

定义人类Person、学生类Student、教师类Teacher、测试类Main

说明:
实现类的继承使用extends关键字,充分体现代码的可重用性

代码:
Person类

public class Person {
    //年龄
    private String name;
    //性别
    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 Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void say(){
        System.out.println("---我是普通人---");
    }
}

Student类(继承Person 类)

public class Student extends Person{
    //成绩
    private double grade;
    public double getGrade() {
        return grade;
    }
    public void setGrade(double grade) {
        this.grade = grade;
    }
    public Student(String name, int age, double grade) {
        //调用父类构造
        super(name,age);
        this.grade = grade;
    }
    @Override
    public void say() {
        //调用父类方法
        super.say();
        System.out.println("我是学生!");
    }

}

Teacher类(继承Person 类)

public class Teacher extends Person{
    //薪资
    private double pay;
    public double getPay() {
        return pay;
    }
    public void setPay(double pay) {
        this.pay = pay;
    }
    public Teacher(String name, int age, double pay) {
        super(name, age);
        this.pay = pay;
    }
    @Override
    public void say() {
        //调用父类
        super.say();
        System.out.println("我是老师!");
    }
}

测试类

public class Main {
    public static void main(String[] args) {
        Student student = new Student("张三",18,95);
        student.say();
        System.out.println("名字:"+student.getName());
        System.out.println("年龄:"+student.getAge());
        System.out.println("成绩:"+student.getGrade());

        Teacher teacher = new Teacher("黄冈",45,6500);
        teacher.say();
        System.out.println("名字:"+teacher.getName());
        System.out.println("年龄:"+teacher.getAge());
        System.out.println("薪资:"+teacher.getPay());
    }
}

结果
JAVA基础-java继承类实现_第1张图片

你可能感兴趣的:(java基础,java)