Test.java:
package cn.xxx.demo;
/*
* 测试类
* 1. 实现动物和Cat,Dog多态调用
* 2. 做类型的强制转换,调用子类的特有功能
*/
public class Test {
public static void main(String[] args) {
//两个子类,使用两次多态调用
Animal a1 = new Cat(); // 多态, 类型自动提升。 Cat和Dog都是Animal的子类。
Animal a2 = new Dog();
//a1,a2调用其父类共有方法
a1.eat();
a2.eat();
//类型向下转型,强制转换,调用子类的特有方法。
if(a1 instanceof Cat){ // 类型强制转换之前先判断是否是Cat的一个实例
Cat c = (Cat)a1; // 类型强制转换
c.catchMouse();
}
if(a2 instanceof Dog){
Dog d = (Dog)a2; // 类型强制转换
d.lookHome();
}
}
}