java的多态数组

多态数组

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

package com.hspedu.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;
    }
}

package com.hspedu.polyarr;

public class Student extends  Person{
    
    
    private double score;

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

        return  super.say()+"score=" + score;
    }
}

package com.hspedu.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;
    }
    //重写父类的方法

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

package com.hspedu.polyarr;

public class ployArray {
    
    
    public static void main(String[] args) {
    
    

        Person [] persons = new Person[5];
        persons[0] = new Person("jack",20);
        persons[1]= new Student("tom",21,66);
        persons[2] = new Student("heihuj",26,98);
        persons[3]= new Teacher("semi",18,8734);
        persons[4] = new Teacher("ligui",12,5849);

        //遍历数组
        for (int i = 0; i < persons.length ; i++) {
    
    
            System.out.println( persons[i].say());
            //编译类型是persons ,运行类型看后面
            //动态绑定
        }
    }
}

猜你喜欢

转载自blog.csdn.net/z2768557792/article/details/124515696