[Java] 对象转型-02

来源:互联网 发布:中兴无线软件开发 编辑:程序博客网 时间:2024/05/16 08:35
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");        }    }}

原创粉丝点击