对象的上下转型

安全性
对象的向上转型是安全的。(多态的写法)
向下转型是不安全的,可能会出现类转换异常。
为什么需要向下转型
对象一旦向上转型为父类,那么就无法调用子类原本特有的内容。
解决方法:
使用对象的向下转型【还原】
如何安全向下转型
instanceof关键字
判断前面的对象能不能作为后面类型的实例,结果布尔值
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| abstract class Animal { public abstract void eat(); }
class Dog extends Animal {
@Override public void eat() { System.out.println("狗吃骨头"); }
public void watchHouse() { System.out.println("看家"); } }
class Cat extends Animal {
@Override public void eat() { System.out.println("猫吃鱼"); }
public void catchMouse() { System.out.println("抓老鼠"); } }
public class Test { public static void main(String[] args) { Animal ani = new Dog(); ani.eat(); if (ani instanceof Dog) { Dog dog = (Dog) ani; dog.watchHouse(); } else if (ani instanceof Cat) { Cat cat = (Cat) ani; cat.catchMouse(); } System.out.println(ani instanceof Animal); } }
|

注意:
接口和实现类之间也有上下转型,instanceof对于接口和实现关系的判断同样准确。