[Java] 对象转型-02

package com.bjsxt.chap03;

public class Cast_02 {

    public static void main(String[] args) {
        Cast_02 test = new Cast_02();
        Animal a = new Animal("AnimalName");
        Cat c = new Cat("catName", "blue");
        Dog d = new Dog("dogName", "block");
        test.f(a);
        test.f(c);
        test.f(d);
    }
    public void f(Animal a) {
        System.out.println("name : " + a.name);
        if (a instanceof Cat) {
            Cat cat = (Cat)a;
            System.out.println(" " + cat.eyescolor + " eyes");
        } else if (a instanceof Dog) {
            Dog dog = (Dog)a;
            System.out.println(" " + dog.furcolor + " fur");
        }
    }
}

原文地址:https://www.cnblogs.com/robbychan/p/3786589.html