如何才能调用子类特有的属性和方法?
Man m1 = (Man)p2;
使用强制类型转换符 向下转型
Man m1 = (Man)p2;
m1.earnMoney();
m1.isSmoking =true;
Woman w1 = (Woman)p2;
w1.goShopping();报错
使用强转时,可能会出现ClassCastException的异常
instanceof:
a instanceof A:判断对象a是否是A的实例,如果是,返回true,如果不是,返回false
if(p2 instanceof Woman){
Woman w1 = (Woman)p2;
w1.goShooping();
System.out.println(“Woman*”)
}
if(p2 instanceof Man){
Man m1 = (Man)p2;
m1earnMoney();
System.out.println(“Man*”)
}
使用情景:为了避免在向下转型时出现ClassCastException的异常,我们在向下转型之前,先进行instanceof判断,一旦返回true,就向下转型,如果不是,返回false。
如果a instanceof A返回true,则a instanceof B也返回true
其中类 B时类A的父类
多态时编译时行为还是运行时的行为。
运行时行为