day09-用instanceof关键字进行类型判断
This commit is contained in:
38
day10/src/com/inmind/duotai08/downcast/Demo11.java
Normal file
38
day10/src/com/inmind/duotai08/downcast/Demo11.java
Normal file
@@ -0,0 +1,38 @@
|
||||
package com.inmind.duotai08.downcast;
|
||||
/*
|
||||
如何在代码中判断出当前的多态父类类型是不是对应的子类类型呢?
|
||||
instanceof 关键字
|
||||
多态类型 instanceof 子类类型 会有一个返回值 boolean
|
||||
true: 多态类型就是子类类型,(animal是一个猫)
|
||||
false:多态类型就不是子类类型,(animal不是一个猫)
|
||||
*/
|
||||
public class Demo11 {
|
||||
public static void main(String[] args) {
|
||||
//来一只狗
|
||||
Dog dog = new Dog();
|
||||
//来一只猫
|
||||
Cat cat = new Cat();
|
||||
//假设每个子类对象都要执行同一段代码,再调用eat,并调用各自的独有的功能
|
||||
work(dog);
|
||||
work(cat);
|
||||
}
|
||||
|
||||
//使用多态的好处,定义一个方法
|
||||
public static void work(Animal animal) {//多态的好用,向上转型
|
||||
System.out.println(1);
|
||||
System.out.println(2);
|
||||
System.out.println(3);
|
||||
animal.eat();
|
||||
|
||||
//在进行向下转型时,必须先判断是否是该类型
|
||||
if (animal instanceof Dog) {
|
||||
Dog d = (Dog) animal;
|
||||
d.watchDoor();
|
||||
}
|
||||
|
||||
if (animal instanceof Cat) {
|
||||
Cat c = (Cat) animal;
|
||||
c.catchMouse();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user