1. 程式人生 > 其它 >Java基礎-多型陣列

Java基礎-多型陣列

package com.hspedu.polyarray_;

import org.junit.Test;

public class TestPolyArray {
    /**
     * 多型陣列
     */
    @Test
    public void testPolyArray() {
        Animal[] animals = new Animal[3];
        animals[0] = new Cat("小白貓", 2);
        animals[1] = new Cat("小花貓", 3);
        animals[2] = new
Dog("小黑狗", 5); // 呼叫父類的通用方法 for (Animal animal : animals) { animal.showInfo(); } // 呼叫子類的獨有的方法 for (Animal animal : animals) { if (animal instanceof Cat) { // Cat cat = (Cat) animal; // cat.jump(); ((Cat) animal).jump(); }
if (animal instanceof Dog) { ((Dog) animal).run(); } } } } class Animal { private String name; private int age; public Animal(String name, int age) { this.name = name; this.age = age; } public void showInfo() { System.out.println(
"info: " + name + ", " + age); } } class Cat extends Animal { private String name; private int age; public Cat(String name, int age) { super(name, age); this.name = name; this.age = age; } public void jump() { System.out.println(name + " jump"); } } class Dog extends Animal { private String name; private int age; public Dog(String name, int age) { super(name, age); this.name = name; this.age = age; } public void run() { System.out.println(name + " run"); } }