1、什么是向上转型?
把子类对象直接赋给父类引用叫向上转型(upcasting),向上转型不用强制转型。
2、为什么要向上转型?
优点:
一个是我们不必知道正在处理的对象的确切类型,这一切都交给多态处理即可;
另一个是可以简化代码数量;
缺点:
不能使用子类中特有的类
3、如何向上转型?
Animal animal = new Cat();
animal.sayAnimal();
animal.sayCat();//编译报错,父类对象无法调用子类的方法
4、什么是向下转型?
把指向子类对象的父类引用赋给子类引用叫向下转型(downcasting),要强制转型
5、为什么要向下转型?
便于程序的扩展,可以调用更多子类的方法。
6、如何向下转型?
Animal animal = new Cat();
Cat cat2 = (Cat) animal;
cat2.sayAnimal();
cat2.sayCat();
为了安全,最好的向下转型方式为:
Animal animal = new Cat();
if(animal instanceof Cat){
Cat cat2 = (Cat) animal;
cat2.sayAnimal();
cat2.sayCat();
}
补充知识点:
instanceof是Java的一个二元操作符(运算符),也是Java的保留关键字。它的作用是判断其左边对象是否为其右边类的实例,返回的是boolean类型的数据,用它来判断某个对象是否是某个Class类的实例。
用法:boolean result = object instanceof class
7、不安全的向下转型:编译正常,运行报错
Cat cat = (Cat) new Animal();
cat.getHead();
cat.getEyes();
运行时报错如下:
父类对象不能转换为子类对象,需要现将子类对象向上转型为父类对象之后,再将父类对象向下转型为子类对象。
Exception in thread "main" java.lang.ClassCastException: com.etc.demo.Animal cannot be cast to com.etc.demo.Cat
8、错误的向下转型:编译正常,运行报错
Animal animal = new Cat();
Dog dog = (Dog) animal;
dog.sayAnimal();
dog.sayDog();
运行时报错如下:
两个子类对象不能相互转换,猫不能变成狗。
Exception in thread "main" java.lang.ClassCastException: com.etc.demo.Cat cannot be cast to com.etc.demo.Dog