1、向上转型:当把子类的对象赋值给父类的变量时,编译期间会发生自动类型提升。
2、向下转型:当把父类的变量的值重新赋值给一个子类的变量时,需要强制类型转换。
向下转型有风险:可能会发生ClassCastException类型转换异常。
向下转型要成功:当这个父类的变量中存储的实际的对象类型 <= 强制转换的子类类型。
class Person{ //... } class Woman extends { //.. } class ChineseWoman extends Woman{ //.. } Person p1 = new Person(); Person p2 = new Woman(); Person p3 = new ChineseWoman(); Woman w1 = (Woman)p1;//错误 Woman w2 = (Woman)p2;//可以 Woman w3 = (Woman)p3;//可以
3、关键字:instanceof
它用于判断xx是否是谁的实例对象。
变量/对象 instanceof 类型
上面的表达式运算结果是true/false.
class Person{ //... } class Woman extends { //.. } class ChineseWoman extends Woman{ //.. } Person p1 = new Person(); Person p2 = new Woman(); Person p3 = new ChineseWoman(); System.out.println(p1 instanceof Woman);//false System.out.println(p2 instanceof Woman);//true System.out.println(p3 instanceof Woman);//true