关闭

JAVA运算符 instanceof

标签: javainstanceof实例
316人阅读 评论(0) 收藏 举报
分类:

判断对象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
*/

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3435次
    • 积分:131
    • 等级:
    • 排名:千里之外
    • 原创:9篇
    • 转载:3篇
    • 译文:0篇
    • 评论:2条
    文章分类