栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java的多态数组

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 ,运行类型看后面
            //动态绑定
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/848095.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号