Java练习(二十九)---多态数组

该博客展示了Java中类的定义及其实例化,包括Person类作为父类,Student和Teacher子类的继承与扩展。子类分别增加了score和salary属性,并覆盖了say方法以展示这些附加信息。在Test类中创建并初始化了Person对象数组,打印了每个对象的姓名、年龄以及子类特有的分数和工资。
摘要由CSDN通过智能技术生成

父类

public class person {
    private String name;
    private int age;

    public person(String name, int age) {
        this.name = name;
        this.age = 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 say(){
        return "姓名:"+name +"年龄:"+age;
    }
}

子类Student

public class Student extends person{
    private double score;

    public Student(String name, int age, double score) {
        super(name, age);
        this.score = score;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    @Override
    public String say() {
        return super.say()+"分数:"+score;
    }
}

子类Teacher

public class Teacher extends person{
    private double salary;

    public Teacher(String name, int age, double salary) {
        super(name, age);
        this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String say() {
        return super.say()+"工资:"+salary;
    }
}

调用类

public class Test {
    public static void main(String[] args) {
        person[] p = new person[5];
        p[0] = new person("张三",18);
        p[1] = new Student("李四",10,100.9);
        p[2] = new Student("王五",13,54.9);
        p[3] = new Teacher("小王",24,3000.8);
        p[4] = new Teacher("小李",23,3400.76);

        for (int i = 0; i < p.length; i++) {
            System.out.println(p[i].say());
        }
    }
}

输出结果:
姓名:张三年龄:18
姓名:李四年龄:10分数:100.9
姓名:王五年龄:13分数:54.9
姓名:小王年龄:24工资:3000.8
姓名:小李年龄:23工资:3400.76

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值