软件编程
位置:首页>> 软件编程>> java编程>> Java关键字instanceof的两种用法实例

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

作者:junjie  发布时间:2023-07-31 06:24:50 

标签:Java,instanceof,用法

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。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com