Java学习之运算符instanceof使用场景

Java学习之运算符instanceof使用场景

1.意义

instanceof是二元运算符,用于判断对象是否为特定类的实例。

2.用法

boolean result = object instanceof class

3.举例分析

class Uncle{}
class Pare{}
class Pare1 extends Pare{}
class Pare2 extends Pare1{}
class Pare3 {
  public static void main(String[] args){
   Uncle  u  = new Uncle();
   Pare   p  = new Pare();
   Pare1  p1 = new Pare1();
   Pare2  p2 = new Pare2();

//本类对象是本类的实例
if ( p instanceof Pare)
 {System.out.println("p instanceof Pare");}

//子类对象是父类的实例
 if (!( p1 instanceof Pare))
   {System.out.println("p1 not instanceof Pare");}
else
   {System.out.println("p1  instanceof Pare");}
 
//父类对象不是子类的实例
 if (p1 instanceof Pare2)
   {System.out.println("p1 instanceof Pare2");}
 else
   {System.out.println("p1 not instanceof Pare2");}

 /*if (p instanceof Uncle)
 {System.out.println("p instanceof Uncle");}
 else
 {System.out.println("p not instanceof Uncle");}*/
  if (null instanceof String)
   {System.out.println("null instanceof String");}  else
   {System.out.println("null not instanceof String");}

Shape s = new Rect(10,30);//父类声明引用子类实例,向上转型
s = new Triangle(5,5,8);
s = new Circle(12.5);

 java.lang.ClassCastException: Circle cannot be cast to Triangle
//Triangle triangle =(Triangle)s  //向下转型抛出运行时异常
//triangle.drawTri();
        
   if(s instanceof Rect){     //避免向下转型抛出运行时异常
        Rect rectangle = (Rect)s;
        rectangle.drawRect();
   } else if (s instanceof Triangle){
        Triangle triangle =(Triangle)s;
        triangle.drawTri();
   } else if (s instanceof Circle){
        Circle circle = (Circle) s;
        circle.drawCir();
   }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值