- /*
- 向下转型需要注意:
- 父类型向下转成子类型,因为子类型不唯一,所以需要进行判断
- 如何判断对象类型呢?
- 用到一个关键字:instanceof
- */
- class CastDemo
- {
- public static void main(String[] args)
- {
- Animal ani1=new Cat();
- ani1.eat();
- if(ani1 instanceof Cat)
- {
- Cat cat2=(Cat)ani1;
- cat2.CatchMouse();
- }
- else
- {
- System.out.println("类型转换失败!");
- }
- }
- }
- abstract class Animal
- {
- abstract void eat();
- }
- class Dog extends Animal
- {
- void lookhome()
- {
- System.out.println("看家");
- }
- void eat()
- {
- System.out.println("狗 吃肉");
- }
- }
- class Cat extends Animal
- {
- void CatchMouse()
- {
- System.out.println("猫 抓老鼠");
- }
- void eat()
- {
- System.out.println("猫 吃鱼");
- }
- }
复制代码 |
|