Skip to content

多态数组


基本介绍

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

代码示例

建立父类 person,子类 student,teacher,boss,设置共有方法 say(),用 for 循环遍历数组,使用 instance of 判断并调用独有的方法

java
//父类
package polyarry;

public class person {
    int age;
    String name;

    public person(){

    }

    public person(int age, String name) {
        this.age = age;
        this.name = name;
    }
    public void say(){
        System.out.println("我是person类");
    }
}

//子类
package polyarry;

public class student extends person{
    double score;

    public student(int age, String name, double score) {
        super(age, name);
        this.score = score;
    }
    public void say(){
        System.out.println("student类\nage:" + age +"\nname:" + name + "\nscore:" + score+ "\n===============");
    }
    public void learn(){
        System.out.println("调用student类的learn()方法~~我的分数是:" + score);
    }
}

package polyarry;

public class teacher extends person{
    public teacher(int age, String name) {
        super(age, name);
    }
    public void say(){
        System.out.println("teacher类\nage:" + age +"\nname:" + name + "\n===============");
    }
    public void teach(){
        System.out.println("调用teacher类的teach()方法~~");
    }

}

package polyarry;

public class boss extends person{
    public boss(int age, String name) {
        super(age, name);
    }
    public void say(){
        System.out.println("boss类\nage:" + age +"\nname:" + name+ "\n===============");
    }
    public void conference(){
        System.out.println("调用boss类的conference()方法~~");
    }
}

// 主类
package polyarry;

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

        person[] p = new person[4];

        p[0] = new student(18, "jackson", 95.5);
        p[1] = new teacher(35, "smith");
        p[2] = new boss(26, "天霸");
        p[3] = new student(18, "tom", 65);

        //由于是父类指向子类,需要向下转型
        System.out.println("首先调用所有类的say方法" + "\n===============");
        for (int i = 0; i < p.length; i++) {
            p[i].say();
        }
        System.out.println("遍历每一个子类对象,调用独有的方法\n");
        for (int i = 0; i < p.length; i++) {
            if (p[i] instanceof student) {
                student stu = (student) p[i];
                stu.learn();
            }else if(p[i] instanceof teacher){
                teacher tech = (teacher) p[i];
                tech.teach();
            }else if(p[i] instanceof boss){
                boss bos = (boss) p[i];
                bos.conference();
            }else{
                System.out.println("你的类型不正确");
            }
        }
    }
}

//运行结果
首先调用所有类的say方法
===============
student类
age:18
name:jackson
score:95.5
===============
teacher类
age:35
name:smith
===============
boss类
age:26
name:天霸
===============
student类
age:18
name:tom
score:65.0
===============
遍历每一个子类对象,调用独有的方法

调用student类的learn()方法~~我的分数是:95.5
调用teacher类的teach()方法~~
调用boss类的conference()方法~~
调用student类的learn()方法~~我的分数是:65.0