[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");
        }
    }
}

posted @ 2013-11-24 08:07  小尼人00  阅读(109)  评论(0编辑  收藏  举报