day10--用instanceof关键字进行类型判断
This commit is contained in:
@@ -7,6 +7,11 @@ package com.inmind.object_cast09;
|
||||
对象的向上转型和向下转型:就是引用数据类型的类型转换
|
||||
|
||||
注意:多态的向下转型,一定要是对应的类型才能转换,否则就报ClassCastException(类型转换异常)
|
||||
--------------------------------------
|
||||
如何在代码中判断出当前多态父类类型是不是对应的子类类型呢??
|
||||
instanceOf 关键字返回一个boolean
|
||||
true:就是该类型
|
||||
false:不是
|
||||
*/
|
||||
public class Demo10 {
|
||||
public static void main(String[] args) {
|
||||
@@ -14,12 +19,16 @@ public class Demo10 {
|
||||
Animal animal = new Cat();//小范围的猫对象赋值给大范围的动物类型(安全的向上转型)
|
||||
|
||||
//将这个动物转为猫
|
||||
Cat cat = (Cat) animal;//大范围的动物对象赋值给小范围的猫类型(不安全的向下转型)
|
||||
cat.catchMouse();
|
||||
if (animal instanceof Cat) {
|
||||
Cat cat = (Cat) animal;//大范围的动物对象赋值给小范围的猫类型(不安全的向下转型)
|
||||
cat.catchMouse();
|
||||
}
|
||||
|
||||
//将这个动物转为狗
|
||||
Dog dog = (Dog) animal;//此处报出了java.lang.ClassCastException
|
||||
dog.watchDoor();
|
||||
if (animal instanceof Dog) {
|
||||
Dog dog = (Dog) animal;//此处报出了java.lang.ClassCastException
|
||||
dog.watchDoor();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user