如何才能知道一个父类引用的对象,本来是什么子类?
格式:
对象 instanceof 类名称
这将会得到一个boolean值结果,也就是判断前面的对象能不能当做后面类型的实例。
1 public class Demo02 {
2 public static void main(String[] args) {
3
4 Animal0 animal = new Dog0(); // 本来是一只狗
5 animal.eat(); // 狗吃SHIT
6
7 giveMeAPet(new Dog0());
8 }
9
10 //giveMeAPet这个方法只是要一只动物,不知道给的动物是狗还是猫,所以要判断一下
11 public static void giveMeAPet (Animal0 animal){
12
13 // 如果希望掉用子类特有方法,需要向下转型
14 // 判断一下父类引用animal本来是不是Dog
15 if (animal instanceof Dog0) {
16 Dog0 dog = (Dog0) animal;
17 dog.watchHouse();
18 }
19
20 // 判断一下animal本来是不是Cat
21 if (animal instanceof Cat0) {
22 Cat0 cat = (Cat0) animal;
23 cat.catchMouse();
24 }
25 }
26
27 }