day09-用instanceof关键字进行类型判断

This commit is contained in:
2026-01-25 11:04:49 +08:00
parent 239ccdd278
commit df9c7fc6f9

View 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();
}
}
}