public class Test {
public static void main(String[] args) {
Animal a1 = new Cat();
Animal a2 = new Dog();
//a1,a2调用父类共有方法,运行走子类的重写
a1.eat();
a2.eat();
//类型强制转换,向下转型,调用子类的特有方法
Cat c = (Cat)a2;
c.catchMouse();
运行结果:
Exception in thread "main" 猫吃鱼
狗吃狗粮
java.lang.ClassCastException: Dog cannot be cast to Cat
at Test.main(Test.java:11)
为了防止发生异常,a1属于Cat对象,可以转成Cat,a2属于Dog对象,可以转成Dog.
因此用instanceof进行判断
public class Test {
public static void main(String[] args) {
Animal a1 = new Cat();
Animal a2 = new Dog();
//a1,a2调用父类共有方法,运行走子类的重写
a1.eat();
a2.eat();
//类型强制转换,向下转型,调用子类的特有方法
if(a1 instanceof Cat){
Cat c = (Cat)a1;
c.catchMouse();
}
if(a2 instanceof Dog){
Dog d = (Dog)a2;
d.lookHome();
}
}
}
运行结果:
猫吃鱼
狗吃狗粮
猫抓老鼠
狗在看家