JAVA中的多态数组

数组的定义类型为父类类型,里面保存的实际元素为子类元素

public class Ploy_array {
    public static void main(String[] args) {
        Person[] persons = new Person[5];
        persons[0] = new Person("tom",20);
        persons[1] = new Student("jack",18,70);
        persons[2] = new Student("smith",18,90);
        persons[3] = new Teacher("li",65,10000);
        persons[4] = new Teacher("wang",35,15000);
        // 遍历
        for(int i = 0; i < persons.length; i++){
            /*类型判断 + 向下转型*/
            // 判断运行类型是不是Student
            if(persons[i] instanceof Student){
                // 方法一 匿名方式调用方法
                // ((Student) persons[i]).study();
                // 方法二
                Student student = (Student)persons[i];
                System.out.println(student.study());
            }
            else if(persons[i] instanceof Teacher){
                System.out.println(((Teacher) persons[i]).teach());
            }
            else if(persons[i] instanceof Person){
                System.out.println(((Person) persons[i]).say());
            }
            else{
                System.out.println("类型有误");
            }
        }
    }
}
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;
    }
}
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;
    }
    public String say(){
        return super.say() +"\t" + score;
    }
    public String study(){
        return getName() + "学生正在学习";
    }
}
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;
    }
    public String say(){
        return super.say() +  "\t" + salary;
    }
    public String teach(){
        return getName() + "老师正在授课";
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值