day10-用instanceof关键字进行类型判断
This commit is contained in:
@@ -0,0 +1,44 @@
|
|||||||
|
package com.inmind.object_cast10;
|
||||||
|
/*
|
||||||
|
如何在代码中判断出当前的多态父类类型是不是对应的子类类型呢?
|
||||||
|
instanceof 关键字
|
||||||
|
多态类型 instanceof 子类类型 会有一个返回值 boolean
|
||||||
|
true: 多态类型就是子类类型,(animal是一个猫)
|
||||||
|
false:多态类型就不是子类类型,(animal不是一个猫)
|
||||||
|
*/
|
||||||
|
public class Demo11 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//来一只猫和狗
|
||||||
|
Cat cat = new Cat();
|
||||||
|
Dog dog = new Dog();
|
||||||
|
eat(cat);
|
||||||
|
eat(dog);
|
||||||
|
}
|
||||||
|
//推导多态的好处:以不变应万变
|
||||||
|
public static void eat(Animal animal) {//Animal a = cat|dog; 多态
|
||||||
|
System.out.println("动物开始吃:");
|
||||||
|
animal.eat();
|
||||||
|
//动物吃完之后,想让它干点活,如果是狗看门,如果是猫抓老鼠
|
||||||
|
if (animal instanceof Dog) {//转换成指定子类对象,调用独有功能
|
||||||
|
Dog dog = (Dog) animal;
|
||||||
|
dog.lookHome();
|
||||||
|
}
|
||||||
|
if (animal instanceof Cat) {//使用instanceof,避免了向下转型的风险!!
|
||||||
|
Cat cat = (Cat) animal;
|
||||||
|
cat.catchMouse();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*//定义一个猫吃东西的方法
|
||||||
|
public static void eat(Cat cat) {//Cat cat = cat;
|
||||||
|
System.out.println("动物开始吃:");
|
||||||
|
cat.eat();
|
||||||
|
}
|
||||||
|
//定义一个狗吃东西的方法
|
||||||
|
public static void eat(Dog dog) {//Dog dog = dog;
|
||||||
|
System.out.println("动物开始吃:");
|
||||||
|
dog.eat();
|
||||||
|
}*/
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user