使用instanceof 避免类型转化问题,在进行类型转换的时候进行对比
package com.imooc;
public class Initail {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
Aninmal obj1 = new Aninmal();
Aninmal obj2 = new Dog();//父类的应用是可以指向多态的
//Dog obj3 = new Aninmal();//错误的指向方法
Aninmal obj3 =new Cat();
obj1.eat();
obj2.eat();
obj3.eat();
Dog obj4 =new Dog();
obj4.watchDoor();
*/
Dog dog = new Dog();
Aninmal aninmal = dog ;//自动类型提升 向上类型转换
if (aninmal instanceof Dog){
Dog dog2 =(Dog)aninmal;//向下类型转化 强制类型转化
}else{
System.out.println("类型无法转化成dog类型");
}
if(aninmal instanceof Cat){
Cat cat = (Cat)aninmal; //编译时 Cat类型 2运行时 Dog类型
}else{
System.out.println("无法进行类型转化");
}
}
}