作用:判断一个对象是否属于一个类
格式:对象 instanceof 类 返回布尔类型
我们先来建一个父类Animal,以及子类Dog,Cat类:
package com.java1234.chap03.sec14; public class Animal { public void say(){ System.out.println("我是一个动物"); } }
package com.java1234.chap03.sec14; public class Dog extends Animal{ public void say(){ System.out.println("我是一只狗"); } }
public class Cat extends Animal{ public void say(){ System.out.println("我是一只猫"); } }
我们搞个测试类:
package com.java1234.chap03.sec14; public class Test { public static void main(String[] args) { Animal dog=new Dog(); System.out.println("dog对象是否属于Animal类:"+(dog instanceof Animal)); System.out.println("dog对象是否属于Dog类:"+(dog instanceof Dog)); System.out.println("dog对象是否属于Cat类:"+(dog instanceof Cat)); } }
运行输出:
dog对象是否属于Animal类:true
dog对象是否属于Dog类:true
dog对象是否属于Cat类:false
通过instanceof我们可以确保向下转型的不出问题;
我们给Dog类,Cat类加各自的方法;
package com.java1234.chap03.sec14; public class Dog extends Animal{ public void say(){ System.out.println("我是一只狗"); } public void f1(){ System.out.println("汪汪..."); } }
package com.java1234.chap03.sec14; public class Cat extends Animal{ public void say(){ System.out.println("我是一只猫"); } public void f2(){ System.out.println("我喜欢吃鱼"); } }
package com.java1234.chap03.sec14; public class Test { public static void doSomeThing(Animal animal){ animal.say(); if(animal instanceof Dog){ ((Dog) animal).f1(); }else if(animal instanceof Cat){ ((Cat) animal).f2(); } } public static void main(String[] args) { Animal dog=new Dog(); System.out.println("dog对象是否属于Animal类:"+(dog instanceof Animal)); System.out.println("dog对象是否属于Dog类:"+(dog instanceof Dog)); System.out.println("dog对象是否属于Cat类:"+(dog instanceof Cat)); doSomeThing(new Dog()); doSomeThing(new Cat()); } }
运行输出:
dog对象是否属于Animal类:true
dog对象是否属于Dog类:true
dog对象是否属于Cat类:false
我是一只狗
汪汪...
我是一只猫
我喜欢吃鱼