慕无忌7406412
2019-04-01 08:12
public class Initial2 {
@SuppressWarnings("unused")
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog dog=new Dog();
Animal animal=dog;//向上类型转换,隐式转换
if(animal instanceof Dog){
Dog dog2=(Dog)animal;//向下类型转换,强制类型转换
System.out.println("Dog型转换成了Animal型了");
}else{
System.out.println("Dog型不能转换成Animal型");
}
if(animal instanceof Cat){
Cat cat=(Cat)animal;
}else{
System.out.println("不能转换成Cat型");
}
System.out.println(dog);
System.out.println(animal);
System.out.println(dog2);//难道强制转换的对象不能打印
}
}
dog2对象在if语句中,所以才打印不出来,有可能不执行
public static void main(String[] args) {
// TODO Auto-generated method stub
dog dog1=new dog();
dog dog2=new dog();
cat cat1=new cat();
animal animal1=cat1;
if(animal1 instanceof dog)
{
dog1=(dog)animal1;
System.out.println("狗可以转化成动物类");
}
else
{
System.out.println("狗不可以转化成动物类");
}
if(animal1 instanceof cat)
{
cat1=(cat)animal1;
System.out.println("猫可以转化成动物类");
}
else
{
System.out.println("猫不可以转化成动物类");
}
System.out.println(dog1);
System.out.println(animal1);
System.out.println(cat1);
}
}
不是Dog型转换成了Animal型了
是把Animal型强制转换成Dog型
建议多看几遍
强制转换完的对象也是对象,当然可以打印。你的错误在于dog2在if{}里,外面取不到,
把System.out.println(dog2);放在第9行就可以了
向下类型转换时容易出错,需要加instanceof可以防止转换出错。
Java入门第二季
531292 学习 · 6327 问题
相似问题