您的位置:首页 > 编程语言 > Java开发

Java关键字instanceof的两种用法实例

2018-10-12 13:51 846 查看

instanceof关键字用于判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)的实例。
 
举个例子:


public interface IObject {
}

public class Foo implements IObject{
}

public class Test extends Foo{
}

public class MultiStateTest {
        public static void main(String args[]){
                test();
        }

        public static void test(){
                IObject f=new Test();
                if(f instanceof java.lang.Object)System.out.println("true");
                if(f instanceof Foo)System.out.println("true");
                if(f instanceof Test)System.out.println("true");
                if(f instanceof IObject)System.out.println("true");
        }
}

输出结果:


true
true
true
true

 
另外,数组类型也可以使用instanceof来比较。比如

String str[] = new String[2];

则str instanceof String[]将返回true。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: