Arthur_Lees的博客

做个吃货,做个傻子

JAVA运算符 instanceof

判断对象object是否为指定类class的实例

例  

boolean result = object instanceof class

当是指定类实例时返回 true 

当不是指定类实例或者object 为null 时返回 false


测试代码

interface A{}
 class B implements A{
  
 }
 class C extends B {
  
 }
 
 class instanceoftest {
  public static void main(String[] args){
     A a=null;
     B b=null;
     boolean res; 
     
     System.out.println("instanceoftest test case 1: ------------------");
       res = a instanceof A; 
       System.out.println("a instanceof A: " + res);
       
       res = b instanceof B;
       System.out.println("b instanceof B: " + res);
       
     System.out.println("/ninstanceoftest test case 2: ------------------");   
     a=new B();
     b=new B();
     
     res = a instanceof A; 
     System.out.println("a instanceof A: " + res);
     
     res = a instanceof B;
     System.out.println("a instanceof B: " + res);
     res = b instanceof A;
     System.out.println("b instanceof A: " + res);
     
     res = b instanceof B;
     System.out.println("b instanceof B: " + res);
    
     System.out.println("/ninstanceoftest test case 3: ------------------");
     B b2=(C)new C();
     
     res = b2 instanceof A;
     System.out.println("b2 instanceof A: " + res);
     
     res = b2 instanceof B;
     System.out.println("b2 instanceof B: " + res);
     
     res = b2 instanceof C;
     System.out.println("b2 instanceof C: " + res);
  }
}

/*
result:

instanceoftest test case 1: ------------------
a instanceof A: false
b instanceof B: false
instanceoftest test case 2: ------------------
a instanceof A: true
a instanceof B: true
b instanceof A: true
b instanceof B: true
instanceoftest test case 3: ------------------
b2 instanceof A: true
b2 instanceof B: true
b2 instanceof C: true
*/

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Arthur_Lees/article/details/51555882
文章标签: java instanceof 实例
个人分类: java
上一篇Java HashMap 的实现原理详解
下一篇TCP服务器端 ServerSocket
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭