instanceof 运算符详解

instanceof是运算符只被用于对象引用变量,检查左边的被测试对象是不是右边类或接口的实例化。 这里有两个方面进行解释: 1.语法:针对声明的类 声明被测试对象的类必须与右边类,要么是继承关系,要么是接口关系,否则会报错。如下: [code="java"] public void TA(Cloneable e){ if(e instanceof String){ } } public void TA(E e){ if(e instanceof String){ } }[/code] 这些无法通过eclipse的语法检测。 2.用法:针对创建的类实例化的类 通过1可以知道左面的声明类和右边的类应该有一个主次关系,但是左面用来实例化的类和右边不一定是主次关系,有可能是同一个父类的同一个子类。这样该运算符的用法就有两层含义:a)检测左面的实例化的类是否是左边的子类b)检测左面的实例化的类是否是其父类的某一个子类 package com.test.instanceof2; class InstanceOf { public static void main(String args[]) { B b = new B(); C c = new C(); D d = new D(); E e = new E(); F f = new F(); H h = new H(); A g = new G(); if (b instanceof B) System.out.println("b is instance of B"); if (c instanceof C) System.out.println("c is instance of C"); if (c instanceof A) System.out.println("c can be cast to A"); if (c instanceof B) System.out.println("c can be cast to B"); if (d instanceof A) System.out.println("d can be cast to A"); if (d instanceof B) System.out.println("d can be cast to B"); if (g instanceof E) System.out.println("d can be cast to B"); System.out.println(); A ob; ob = d; // A reference to d System.out.println("ob now refers to d"); if (ob instanceof D) System.out.println("ob is instance of D"); System.out.println(); ob = c; // A reference to c System.out.println("ob now refers to c"); if (ob instanceof D) System.out.println("ob can be cast to D"); else System.out.println("ob cannot be cast to D"); if (ob instanceof A) System.out.println("ob can be cast to A"); System.out.println(); // all objects can be cast to Object if (b instanceof Object) System.out.println("b may be cast to Object"); if (c instanceof Object) System.out.println("c may be cast to Object"); if (d instanceof Object) System.out.println("d may be cast to Object"); } public void TA(Object e){ if(e instanceof String){ } } } interface A { } class B { int i, j; } class C extends B implements A { int k; } class D extends B implements A { int k; } class E extends B { int k; } class F extends B { int k; } class G implements A{ } class H implements A{ }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值