instaceof关键字的使用
有了对象的多态性以后,内存中实际上是加载了子类特有的属性和方法的,但是由于变量声明为父类类型,导致编译时,只能调用父类中声明的属性和方法。子类特有的属性和方法不能调用。
如何才能调用子类特有的属性和方法?
向下转型:使用强制类型转换符。使用强转时,可能出现ClassCastException的异常
- 例:Man extends Person,Woman extends Person
Person p2 = new Man();
- 此时Person可以向下转型成Man,不能转换成Woman
Man m1 = (Man)p2;
此时可以通过m1.方法(属性)
的形式调用子类Man中的属性和方法Woman w1 = (Woman)p2;
通过w1.方法(属性)
的形式调用子类Woman中的属性和方法时,则会出现ClassCastException的异常
为了避免这种情况的出现,引入了instanceof关键字
instanceof关键字的使用
- a instanceof A:判断对象a是否是类A的实例。如果是,返回true;如果不是,返回false。
- 使用情境:为了避免在向下转型时出现ClassCastException的异常,我们在向下转型之前,先
- 进行instanceof的判断,一旦返回true,就进行向下转型。如果返回false,不进行向下转型。
- 如果 a instanceof A返回true,则 a instanceof B也返回true . 类B是类A的父类
//因为上文中Person p2 = new Man();p2时类Man的一个实例化
//flase
if(p2 instanceof Woman){
Woman w1 = (Woman)p2;
w1.goShopping();
System.out.println("******Woman******");
}
//true
if(p2 instanceof Man){
Man m2 = (Man)p2;
m2.earnMoney();
System.out.println("******Man******");
}
//true
if(p2 instanceof Person){
System.out.println("******Person******");
}
//true
if(p2 instanceof Object){
System.out.println("******Object******");
}