java例程练习(对象转型及instanceof关键字)
2012-04-22 14:07
507 查看
public class Test { public static void main(String[] args) { Animal a = new Animal("name"); Cat c = new Cat("Tom", "Blue"); Dog d = new Dog("Pipi", "Black"); System.out.println(a instanceof Animal); System.out.println(c instanceof Animal); System.out.println(d instanceof Animal); System.out.println(a instanceof Cat); System.out.println(); a = new Dog("Bangbang", "Yellow"); System.out.println(a instanceof Animal); System.out.println(a instanceof Dog); System.out.println(); Dog d1 = (Dog)a; System.out.println(d1 instanceof Animal); System.out.println(d1 instanceof Dog); System.out.println(); Test test = new Test(); test.info(a); test.info(c); test.info(d); test.info(d1); } public void info(Animal a) { System.out.print("" + a.name); if(a instanceof Cat) { Cat cat = (Cat)a; System.out.print(" has " + cat.eyeColor + " eyes"); } else if(a instanceof Dog) { Dog dog = (Dog)a; System.out.print(" has " + dog.furColor + " fur"); } System.out.println(); } } class Animal { public String name; Animal(String name) { this.name = name; } } class Cat extends Animal { public String eyeColor; Cat(String n, String c) { super(n); eyeColor = c; } } class Dog extends Animal { public String furColor; Dog(String n, String c) { super(n); furColor = c; } }
相关文章推荐
- java例程练习(对象转型及instanceof关键字)
- Java面向对象8——对象转型,动态绑定,抽象类,final关键字及接口
- JAVA面向对象-----instanceof 关键字
- Java面向对象-instanceof关键字
- java例程练习(对象类型数据的排序)
- Java面向对象高级--instanceof关键字
- JAVA面向对象-----instanceof 关键字
- java例程练习(super关键字)
- 【自用】Javanote170801(封装、多态、instanceof运算符、对象转换类型、final关键字、参数传递)
- 黑马程序员_Java基础_03面向对象思想(对象转型注意事项、多态、抽象类、final关键字等)
- java例程练习(对象流)
- java例程练习(对象流)
- JAVA_多态性演示a____自动向上转型、向下转型、检查对象是否为某个类型(instanceof)
- java例程练习(static关键字的使用)
- java例程练习(extends关键字)
- java例程练习(对象流)
- JAVA_多态性演示a____自动向上转型、向下转型、检查对象是否为某个类型(instanceof)
- 第二十六、Java面向对象之instanceof 关键字
- java 基础 4 super、final关键字及上转型对象的使用
- java例程练习(对象流)