java-面向对象中级-多态数组(基础)

多态数组(基础)

应用实例:现有一个继承结构如下:要求创建1个Person对象、2个Student 对象和2个Teacher对象, 统一放在数组中,并调用每个对象say方法
本题重点: person[i] 编译类型是 Person ,运行类型是是根据实际情况由JVM来判断,即同编译类型,不同运行类型,对象的多态!

主类-PloyArray

package com.hspedu.poly_.polyarr_;

public class PloyArray {
    public static void main(String[] args) {
        //应用实例:现有一个继承结构如下:要求创建1个Person对象、
        // 2个Student 对象和2个Teacher对象, 统一放在数组中,并调用每个对象say方法

        Person person[] = new Person[5];
        person[0] = new Person("jack",20);
        person[1] = new Student("mary",18,100);
        person[2] = new Student("smith",19,80);
        person[3] = new Teacher("scott",30,19999);
        person[4] = new Teacher("king",50,25000);

        //循环遍历多态数组,调用say
        for (int i = 0; i < person.length; i++) {
            //提示: person[i] 编译类型是 Person ,运行类型是是根据实际情况有JVM来判断
            System.out.println(person[i].say());//动态绑定机制
        }
    }
}

父类-Person

package com.hspedu.poly_.polyarr_;

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 + "\t" + age;
    }
}

子类-Student

package com.hspedu.poly_.polyarr_;

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;
    }

    //重写父类的say方法

    @Override
    public String say() {
        return "学生 "+super.say() + "\t" + "score=" + score;
    }
}

子类-Teacher

package com.hspedu.poly_.polyarr_;

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;
    }
    //重写父类的say方法
    @Override
    public String say() {
        return "老师 "+super.say() + "\t" +"salary=" + salary;
    }
}

运行结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值